你好,游客 登录 注册 搜索
背景:
阅读新闻

使用循环链表实现约瑟夫环(围圈报数问题)

[日期:2016-06-19] 来源:Linux社区  作者:callmebill [字体: ]

刚开始学C,碰到经典的围圈报数问题,现先将实现代码附下:

#include<stdio.h>
#include<stdlib.h>

struct LNODE{            //链表定义
 int data;
 struct LNODE *next;
};
typedef struct LNODE Lnode;
typedef struct LNODE *LinkList;
struct LNODE *create(int s[])      //创建单项循环链表
{
 struct LNODE *head=NULL,*p=NULL,*last=NULL;
 int i=0;
 head=(struct LNODE *)malloc(sizeof(struct LNODE));
 if(!head)
 printf("memory allocation error!");
 if(s[0]!=0)
 {
 
  head->data=s[0];
  head->next=head;
  last=head;
  i++;
  while(s[i]!=0)      //判断是否为0,为0则结束
  {
  p=(struct LNODE*)malloc(sizeof(struct LNODE));
  last->next=p;
  p->data=s[i];  
  p->next=head;
  last=p;
  i++;
  }
 }
 return head;
}
void printlist(struct LNODE *head)    //打印循环链表
{
 struct LNODE *q;
 int i;
 printf("the linked list is :\n");
 if(!head)
  printf("NULL");
 else
 {
  q=head;
  do
  {
  printf("%d\t",q->data);
  q=q->next;
  }while(q!=head);
 }
 printf("\n");
 
}
 
 
int main()
{
 int  circlelist[100],n,i,k=1;
 printf("please input the number:");
 scanf("%d",&n);      //输入人数
 getchar();
 for(i=0;i<n;i++)
  circlelist[i]=i+1;      //给每个人编号
 circlelist[i]=0;        //最后值赋0
 for(i=0;i<=n;i++)
  printf("%d\t",circlelist[i]);    //打印编号
 LinkList p=NULL,q=NULL;
 p=create(circlelist);
 printlist(p);          //打印编号链表
 while(p->data!=p->next->data)    //自身与自身相等时退出循环
 {
  if(k!=3)                //设置报到数3的人退出
  {
  k++;
  q=p;
  p=p->next;
  }
  else
  {
  k=1;
  printf("%d\t",p->data);      //打印先后推出的人员编号
  q->next=p->next;        //删除报3的人员结点
  p=q->next;
  }
 }
 printf("\n%d\n",p->data);

}

刚开始指针定义时都没有赋值为NULL,调试没错误,可是却无法执行。

书中说,建议定义时如果暂时不使用指针,先赋值为NULL,我觉得最好这样做,而且,在使用指针时,都应该判断一下是否为空。

本文永久更新链接地址http://www.linuxidc.com/Linux/2016-06/132457.htm

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款