單鏈表的建立和列印
阿新 • • 發佈:2018-12-10
#include <stdio.h> #include <stdlib.h> //定義連結串列資料結構 struct node { int num; struct node *next; }; //函式宣告 struct node *creat(struct node *); void print(struct node *); void main() { struct node *head; head = NULL; //建立一個空表 head = creat(head); //建立單鏈表 print(head); //列印單鏈表 } struct node *creat(struct node *head) { struct node *p1,*p2; int i = 1; //利用malloc函式向系統申請節點 p1 = p2 = (struct node *)malloc(sizeof(struct node)); //申請節點 printf("輸入大於0的值,小於等於0則結束,值的存放地址為:p1_addr = %d\n",p1); scanf("%d",&p1->num); p1->next = NULL; while(p1->num > 0) { if(head == NULL) head = p1; else p2->next = p1; p2 = p1; p1 = (struct node *)malloc(sizeof(struct node)); p1->next = NULL;//置空 i++; printf("輸入大於0的值,小於等於0則結束,值的存放地址為:p%d_addr = %d\n",i,p1); scanf("%d",&p1->num); } free(p1); p1 = NULL; p2->next = NULL; printf("輸入結束\n"); return head; } void print(struct node *head) { struct node *tmp; tmp = head; printf("連結串列列印開始!!!\n"); while(tmp != NULL) { printf("輸入的值為:num = %d,地址為:addr = %d\n",tmp->num,tmp); tmp = tmp->next; } printf("連結串列列印結束!!!\n"); }
執行結果: