1 void input() { 2 struct stud_node *q; 3 do { 4 q = (struct stud_node*)malloc(sizeof(struct stud_node)); 5 scanf("%d",&q->num); 6 if ( q->num != 0){ 7 scanf("%s %d", q->name, &q->score); 8 if ( head == NULL ) { 9 head = q; 10 head->next = NULL; 11 } 12 if ( tail != NULL ) { //為tail開辟結點 13 tail->next = q; 14 } 15 tail = q; 16 tail->next = NULL; 17 } 18 } while ( q->num != 0); 19 20 }
1 struct stud_node { 2 int num; /*學號*/ 3 char name[20]; /*姓名*/ 4 int score; /*成績*/ 5 struct stud_node *next; /*指向下個結點的指針*/ 6 }; 7 struct stud_node *head, *tail;
單向鏈表的頭尾指針保存在全局變量head
和tail
中。
大概固定的公式:
struct stud_node *head, *tail, *q; //頭, 尾, 相當於用來控制的指針
q = (struct stud_node*)malloc(sizeof(struct stud_node)); //申請動態分配內存
令輸入的元素用 q-> 來指向, 而后先判斷head是否為空, 如果為空, 令head = q;
而后要做的就是讓尾tail一直處於鏈表的尾部, 此處畫圖理解會比較好
總結來說建立鏈表的方法大概是這樣, 死記這個大概的方法, 遇到不同的問題再見機更改就行了