C語言數(shù)據(jù)結(jié)構(gòu)之循環(huán)鏈表的簡單實(shí)例
更新時(shí)間:2017年06月26日 16:15:59 投稿:lqh
這篇文章主要介紹了C語言數(shù)據(jù)結(jié)構(gòu)之循環(huán)鏈表的簡單實(shí)例的相關(guān)資料,需要的朋友可以參考下
C語言數(shù)據(jù)結(jié)構(gòu)之循環(huán)鏈表的簡單實(shí)例
實(shí)例代碼:
# include <stdio.h> # include <stdlib.h> typedef struct node //定義鏈表中結(jié)點(diǎn)的結(jié)構(gòu) { int code; struct node *next; }NODE,*LinkList; /*錯(cuò)誤信息輸出函數(shù)*/ void Error(char *message) { fprintf(stderr,"Error:%s/n",message); exit(1); } //創(chuàng)建循環(huán)鏈表 LinkList createList(int n) { LinkList head; //頭結(jié)點(diǎn) LinkList p; //當(dāng)前創(chuàng)建的節(jié)點(diǎn) LinkList tail; //尾節(jié)點(diǎn) int i; head=(NODE *)malloc(sizeof(NODE));//創(chuàng)建循環(huán)鏈表的頭節(jié)點(diǎn) if(!head) { Error("memory allocation error!/n"); } head->code=1; head->next=head; tail=head; for(i=2;i<n;i++) { //創(chuàng)建循環(huán)鏈表的節(jié)點(diǎn) p=(NODE *)malloc(sizeof(NODE)); tail->next=p; p->code=i; p->next=head; tail=p; } return head; }
第二種方法:
//創(chuàng)建循環(huán)鏈表方法2(軟件設(shè)計(jì)師教程書上的方法) 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); }
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
相關(guān)文章
C語言多種方法實(shí)現(xiàn)一個(gè)函數(shù)左旋字符串中K個(gè)字符
這篇文章主要為大家介紹了C語言多種方法實(shí)現(xiàn)一個(gè)函數(shù),可以左旋字符串中K個(gè)字符,文中附含詳細(xì)的示例講解,有需要的朋友可以借鑒參考下2021-10-10QT實(shí)現(xiàn)將兩個(gè)時(shí)間相加的算法[hh:?mm?+?hh:?mm]的示例代碼
本文主要介紹了QT實(shí)現(xiàn)將兩個(gè)時(shí)間相加的算法[hh:?mm?+?hh:?mm]的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07VC++實(shí)現(xiàn)輸出GIF到窗體并顯示GIF動(dòng)畫的方法
這篇文章主要介紹了VC++實(shí)現(xiàn)輸出GIF到窗體并顯示GIF動(dòng)畫的方法,需要的朋友可以參考下2014-07-07