C语言数据结构之循环链表的简单实例

2025-05-27 0 38

C语言数据结构循环链表的简单实例

实例代码:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41
# 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;

}

第二种方法:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27
//创建循环链表方法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;

}

?

1

2

3

4

5

6

7

8

9

10

11

12
void output(LinkList head)

{

LinkList p;

p=head;

do

{

printf("%4d",p->code);

p=p->next;

}

while(p!=head);

printf("/n");

}

?

1

2

3

4

5

6

7

8

9
void main(void)

{

LinkList head;

int n;

printf("input a number:");

scanf("%d",&n);

head=createList(n);

output(head);

}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 C语言数据结构之循环链表的简单实例 https://www.kuaiidc.com/74066.html

相关文章

发表评论
暂无评论