C語言數據結構之循環鏈表的簡單實例
實例代碼:
# include <stdio.h># include <stdlib.h>typedef struct node //定義鏈表中結點的結構{ int code; struct node *next;}NODE,*LinkList; /*錯誤信息輸出函數*/void Error(char *message){ fprintf(stderr,"Error:%s/n",message); exit(1);}//創建循環鏈表LinkList createList(int n){ LinkList head; //頭結點 LinkList p; //當前創建的節點 LinkList tail; //尾節點 int i; head=(NODE *)malloc(sizeof(NODE));//創建循環鏈表的頭節點 if(!head) { Error("memory allocation error!/n"); } head->code=1; head->next=head; tail=head; for(i=2;i<n;i++) { //創建循環鏈表的節點 p=(NODE *)malloc(sizeof(NODE)); tail->next=p; p->code=i; p->next=head; tail=p; } return head;}
第二種方法:
//創建循環鏈表方法2(軟件設計師教程書上的方法)LinkList createList2(int n){ LinkList head,p; int i; head=(NODE *)malloc(sizeof(NODE)); if(!head) { printf("memory allocation error/n"); exit(1); } head->code=1; head->next=head; for(i=n;i>1;--i) { p=(NODE *)malloc(sizeof(NODE)); if(!p) { printf("memory allocation error!/n"); exit(1); } p->code=i; p->next=head->next; head->next=p; } return head;}
void output(LinkList head){ LinkList p; p=head; do { printf("%4d",p->code); p=p->next; } while(p!=head); printf("/n");}
void main(void){ LinkList head; int n; printf("input a number:"); scanf("%d",&n); head=createList(n); output(head);}
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答
圖片精選