連結串列(頭插法)
阿新 • • 發佈:2018-12-11
#include <stdio.h> #include <stdlib.h> //頭插法 typedef struct stu{ int x; struct stu *next; }s; void create(s *h,int n) { int i; s *p; for(i=0;i<n;i++) { p=(s*)malloc(sizeof(s)); scanf("%d",&p->x); p->next=h->next;//第一個p1指標域是空,h指標域記錄p1地址給p2指標域;也就是說每個節點的指標域是前一個節點地址; h->next=p;//h最後儲存的是最後輸入的一個節點的地址 } } void output(s *h) { s *r;
r=h->next; while(r!=NULL) { printf("%d ",r->x); r=r->next; } printf("\n"); } int main() { int n; s *h; while(scanf("%d",&n)!=EOF) { h=(s*)malloc(sizeof(s)); h->next=NULL; create(h,n); output(h); }
return 0; }