http://blog.csdn.net/morixinguan/article/details/51771633
我們都知道,單向鏈表最后指向為NULL,也就是為空,那單向循環鏈表就是不指向為NULL了,指向頭節點,所以下面這個程序運行結果就是,你將會看到遍歷鏈表的時候就是一個死循環,因為它不指向為NULL,也是周而復始的執行。串成了一個環型。
? ? ?
[cpp]?view plaincopy print?
- #include?<stdio.h>??
- #include?<stdlib.h>??
- typedef?struct?node??
- {??
- ????char?name[20];??
- ????struct?node?*link;??
- }student;??
- ??
- student?*?creat(int?n)????/*建立單鏈表的函數,形參n為人數*/??
- {??
- ????/*?*h保存表頭結點的指針,*p指向當前結點的前一個結點,*s指向當前結點*/??
- ????student?*p,*h,*s;???????
- ????int?i;??
- ????if((h=(student?*)malloc(sizeof(student)))==NULL)?/*分配空間并檢測*/??
- ????{??
- ????????printf("不能分配內存空間!");??
- ????????exit(0);??
- ????}??
- ????h->name[0]='\0';?????/*把表頭結點的數據域置空*/??
- ????h->link=NULL;????????/*把表頭結點的鏈域置空*/??
- ????p=h;????????????????/*p指向表頭結點*/??
- ????for(i=0;i<n;i++)??
- ????{??
- ????????if((s=?(student?*)?malloc(sizeof(student)))==NULL)?/*分配新存儲空間并檢測*/??
- ????????{??
- ????????????printf("不能分配內存空間!");??
- ????????????exit(0);??
- ????????}??
- ????????p->link=s;?/*把s的地址賦給p所指向的結點的鏈域,這樣就把p和s所指向的結點連接起來了*/??
- ????????printf("請輸入第%d個人的姓名",i+1);??
- ????????//指向結構體中的數據???
- ????????scanf("%s",s->name);??
- ????????s->link=NULL;??
- ????????p=s;??
- ????}??
- ????//如果是單向鏈表,這里為NULL,環形鏈表需要指向保存表頭節點的指針。???
- ????p->link=h;???
- ????return(h);??
- }??
- ??
- int?main(void)??
- {??
- ????int?number;???
- ????student?*head;?/*head是保存單鏈表頭結點地址的指針*/??
- ????student?*p;??
- ????printf("請輸入相應的人數:\n");??
- ????scanf("%d",&number);??
- ????head=creat(number);?/*把所新建的單鏈表頭地址賦給head*/??
- ????p=head;??
- ????while(p->link)??
- ????{??
- ????????printf("%s\n",p->name);??
- ????????p=p->link;??
- ????}??
- ??
- ????return?0?;??
- }??