C语言数据结构——链表
技术干货第一时间送达!
今天来介绍一下C语言中常见的一种数据结构——链表
如下是链表的结构示意图:
从示意图中我们可以看到,head头结点指向第一个元素,第一个元素的指针指向第二个元素,第二个元素的指针又指向第三个元素,第三个元素的指针指向null。这样我们就可以通过头指针寻找链表中的元素。
下来我们通过一个具体的实例来深入地了解一下链表,编写一个学生信息的链表结构,并且将链表中的信息进行输出。
struct Student{char name[20];//姓名int id;//学号struct Student* next;//指向下一个节点的指针};int count;//表示链表长度struct Student* create(){struct Student* head = NULL;//初始化链表的头指针struct Student* end, * new;count = 0;//初始化链表长度end = new = (struct Student*)malloc(sizeof(struct Student));//动态分配内存空间printf("请输入姓名,学号\n");scanf("%s", &new->name);scanf("%d", &new->id);while (new->id != 0){count++;if (count == 1){new->next = head;//使得指向为空end = new;//跟踪新加入的节点head = new;//头指针指向首节点}else{new->next = NULL;//新节点的指向为空end->next = new;//原来的为节点指向新节点end = new;//end指向新节点}new = (struct Student*)malloc(sizeof(struct Student));//再次动态分配节点的内存空间scanf("%s", &new->name);scanf("%d", &new->id);}free(new);//释放空间return head;};void show(struct Student* head) {struct Student *temp;int index = 1;printf("有%d位学生:\n",count);temp = head;while (temp != NULL){printf("第 %d 位学生的姓名是:%s,学号是:%d \n", index, temp->name, temp->id);temp = temp->next;index++;}}int main() {struct Student* head;//定义头结点head = create();//创建节点show(head);//输出链表return 0;}
运行结果
关于实例的代码就不多解释了,注释已经很详细了,多看几遍就明白了。
【END】
如果您觉得本篇文章对您有帮助请转发给更多的人
顺手点一下“在看”也是对小编最大的支持
