温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-09-04 13:35:20 来源:脚本之家 阅读:180 作者:lqh 栏目:编程语言

 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);
}

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI