数据结构之单链表(list)
案例:定义三个学生信息,通过第一个学生能够找到第二个学生,通过第二个学生能够找到第三学生
通过第一个学生能够找到第三学生
参考代码:student.c
//student.c:单链表演示
#include <stdio.h>
typedef struct student {
char name[32];
int age;
struct student *next; //保存下一个学生的地址
}stu_t;
int main(void) {
stu_t stu1 = {"刘备", 20, NULL};
stu_t stu2 = {"关羽", 19, NULL};
stu_t stu3 = {"张飞", 18, NULL};
stu_t head;
stu_t tail;
//连接他们
head.next = &stu1;
stu1.next = &stu2;
stu2.next = &stu3;
stu3.next = &tail;
tail.next = NULL;
//通过刘备打印名字 可维护性非常差
printf("%s, %s, %s\n", stu1.name, stu1.next->name, stu1.next->next->name);
//通过head,tail访问
for(stu_t *pnode = &head; pnode != &tail; pnode=pnode->next) {
stu_t *pmid = pnode->next;
if(pmid != &tail)
printf("%s ", pmid->name);
}
printf("\n");
return 0;
}