尾插法創建鏈表


 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 /*
 4 尾插法創建鏈表:尾插法就是每次都把結點插在尾結點后面
 5 總結:尾插法相對頭插法 需要多定義一個指針pt來保存尾結點的地址。
 6 */
 7 typedef struct node
 8 {
 9     int data;
10     struct node * next;
11 }NODE;
12 NODE * createList()
13 {
14     NODE *head = (NODE *)malloc(sizeof(NODE));
15     head->next = NULL;
16     
17     NODE * cur = NULL;
18     NODE * pt = head;//pt保存尾結點的地址,即:pt指向尾結點。
19     int data;
20     printf("請輸入結點的數據\n");
21     scanf("%d",&data);
22 
23     while(data)
24     {
25         cur = (NODE *)malloc(sizeof(NODE));
26         cur->data = data;
27         pt->next = cur;
28         cur->next = NULL;
29         pt = cur;     //pt指向尾結點
30         scanf("%d",&data);
31     }
32     return head;
33 }
34 void traverList(NODE * head)
35 {
36     head = head->next;
37     while(head)
38     {
39         printf("%d",head->data);
40         head = head->next;
41     }
42 }
43 int main(void)
44 {
45 //建立鏈表
46     NODE * head = createList();
47 //遍歷並輸出鏈表
48     traverList(head);
49 
50     return 0;
51 }

 


免責聲明!

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



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