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

