實現一個將輸入的學生成績組織成單向鏈表的簡單函數


 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;

 

單向鏈表的頭尾指針保存在全局變量headtail中。

大概固定的公式: 

struct stud_node *head, *tail, *q;  //頭, 尾, 相當於用來控制的指針
q = (struct stud_node*)malloc(sizeof(struct stud_node));  //申請動態分配內存

令輸入的元素用 q-> 來指向, 而后先判斷head是否為空, 如果為空, 令head = q;

而后要做的就是讓尾tail一直處於鏈表的尾部, 此處畫圖理解會比較好

總結來說建立鏈表的方法大概是這樣, 死記這個大概的方法, 遇到不同的問題再見機更改就行了




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM