// 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; }