学堂 学堂 学堂公众号手机端

在C语言中,可以通过定义结构体来创建链表

lewis 1年前 (2024-02-09) 阅读数 6 #技术

在C语言中,可以通过定义结构体来创建链表。以下是一个简单的例子:

#include<stdio.h> #include<stdlib.h> //定义链表节点结构体 structNode{ intdata; structNode*next; }; //创建新节点 structNode*createNode(intdata){ structNode*newNode=(structNode*)malloc(sizeof(structNode)); if(newNode==NULL){ printf("Memoryallocationfailed\n"); exit(1); } newNode->data=data; newNode->next=NULL; returnnewNode; } intmain(){ //创建链表头指针 structNode*head=NULL; //添加节点到链表 structNode*newNode=createNode(10); head=newNode; newNode->next=createNode(20); newNode=newNode->next; newNode->next=createNode(30); newNode=newNode->next; //遍历链表并打印节点的值 structNode*current=head; while(current!=NULL){ printf("%d",current->data); current=current->next; } return0; }

在上面的代码中,首先定义了一个Node结构体来表示链表节点。然后通过createNode()函数创建新的节点,并通过指针将它们连接在一起形成链表。最后通过遍历链表打印每个节点的值。


版权声明

本文仅代表作者观点,不代表博信信息网立场。

热门