// linkdemo.c -- 链表的基本用法 #include <stdio.h> #include <stdlib.h> #include <string.h> struct data{ char name[20]; struct data *next; }; // 为结构和指向该结构的指针定义 //typedef struct data PERSON; //typedef PERSON *LINK; int main(void){ //头指针、新指针和当前元素指针 struct data *head = NULL; struct data *new1 = NULL; struct data *current = NULL; //添加第一个链表元素 new1 = (struct data *)malloc(sizeof(struct data)); // 建立一个新节点 new1->next = head; // 让表头赋值给下一个节点,这时表头和next储存的指针相同 head = new1; strcpy(new1->name, "Abigail"); //在链表末尾添加一个元素 current = head; while(current->next != NULL){ current = current->next; } new1 = (struct data *)malloc(sizeof(struct data)); current->next = new1; new1->next = NULL; strcpy(new1->name, "Carolyn"); // 在链表的第二个位置添加一个新元素 new1 = (struct data *)malloc(sizeof(struct data)); new1->next = head->next; head->next = new1; strcpy(new1->name, "Beatrice"); // 按顺序打印全部数据 current = head; while(current != NULL){ printf("\n%s", current->name); current = current->next; } printf("\n"); return 0; }