1. 程式人生 > >前插法建立單鏈表(C語言實現)

前插法建立單鏈表(C語言實現)

#include<stdio.h> #include<stdlib.h> struct node{     int data;//結點的資料域     struct node *next;//結點的指標域 }; int main() {     struct node *head,*p;     int i,n;     head = (struct node *)malloc(sizeof(struct node));//為頭結點申請空間     head->next = NULL;//頭結點指標域指向空     printf("請輸入連結串列長度:");     scanf("%d",&n);//輸入表長     for(i=1;i<=n;i++)     {         p = (struct node *)malloc(sizeof(struct node));//為新結點申請空間         scanf("%d",&p->data);//向新結點p的資料域中新增元素         p->next = head->next;         head->next = p;//頭結點的指標域指向新結點     }     while(1)//遍歷元素     {         printf("%d ",p->data);         if(p->next==NULL)             break;//如果是最後一個結點則跳出迴圈         p = p->next;//p指向下一個結點     }     return 0; } 實現過程如下圖: