Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / 使用循环链表实现约瑟夫环(围圈报数问题)

刚开始学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 : ");
 if(!head)
  printf("NULL");
 else
 {
  q=head;
  do
  {
 printf("%d ",q->data);
 q=q->next;
  }while(q!=head);
 }
 printf(" ");
 
}
 
 
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 ",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 ",p->data); //打印先后推出的人员编号
 q->next=p->next; //删除报3的人员结点
 p=q->next;
  }
 }
 printf(" %d ",p->data);}刚开始指针定义时都没有赋值为NULL,调试没错误,可是却无法执行。书中说,建议定义时如果暂时不使用指针,先赋值为NULL,我觉得最好这样做,而且,在使用指针时,都应该判断一下是否为空。本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-06/132457.htm