Chinaunix首页 | 论坛 | 博客
  • 博客访问: 641202
  • 博文数量: 63
  • 博客积分: 1265
  • 博客等级: 中尉
  • 技术积分: 789
  • 用 户 组: 普通用户
  • 注册时间: 2010-04-06 21:54
文章分类

全部博文(63)

文章存档

2017年(1)

2016年(3)

2015年(2)

2013年(5)

2012年(20)

2011年(32)

分类: C/C++

2011-07-03 10:39:54

  1. # include <stdio.h>
  2. # include <stdlib.h>
  3. typedef struct node //定义链表中结点的结构
  4. {
  5.  int code;
  6.  struct node *next;
  7. }NODE,*LinkList;

  8. /*错误信息输出函数*/
  9. void Error(char *message)
  10. {
  11.  fprintf(stderr,"Error:%s/n",message);
  12.  exit(1);
  13. }

  14. //创建循环链表
  15. LinkList createList(int n)
  16. {
  17.  LinkList head; //头结点
  18.  LinkList p; //当前创建的节点
  19.  LinkList tail; //尾节点
  20.  int i;
  21.  head=(NODE *)malloc(sizeof(NODE));//创建循环链表的头节点
  22.  if(!head)
  23.  {
  24.   Error("memory allocation error!/n");
  25.  }
  26.  head->code=1;
  27.  head->next=head;
  28.  tail=head;
  29.  for(i=2;i<n;i++)
  30.  {
  31.   //创建循环链表的节点
  32.   p=(NODE *)malloc(sizeof(NODE));
  33.   tail->next=p;
  34.   p->code=i;
  35.   p->next=head;
  36.   tail=p;
  37.  }
  38.  return head;
  39. }

  40. //创建循环链表方法2(软件设计师教程书上的方法)
  41. LinkList createList2(int n)
  42. {
  43.  LinkList head,p;
  44.  int i;
  45.  head=(NODE *)malloc(sizeof(NODE));
  46.  if(!head)
  47.  {
  48.   printf("memory allocation error/n");
  49.   exit(1);
  50.  }
  51.  head->code=1;
  52.  head->next=head;
  53.  for(i=n;i>1;--i)
  54.  {
  55.   p=(NODE *)malloc(sizeof(NODE));
  56.   if(!p)
  57.   {
  58.    printf("memory allocation error!/n");
  59.    exit(1);
  60.   }
  61.   p->code=i;
  62.   p->next=head->next;
  63.   head->next=p;
  64.  }
  65.  return head;
  66. }

  67. void output(LinkList head)
  68. {
  69.  LinkList p;
  70.  p=head;
  71.  do
  72.  {
  73.   printf("%4d",p->code);
  74.   p=p->next;
  75.  }
  76.  while(p!=head);
  77.  printf("/n");
  78. }

  79. void main(void)
  80. {
  81.  LinkList head;
  82.  int n;
  83.  printf("input a number:");
  84.  scanf("%d",&n);
  85.  head=createList(n);
  86.  output(head);
  87. }
阅读(4227) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~