关于约瑟夫环的C语言数据结构,这个程序在哪里出错了?

//n个人围圈报数,报m出列,最后剩下的是几号?#include<stdio.h>#include<stdlib.h>typedefstructnode{intdata;... //n个人围圈报数,报m出列,最后剩下的是几号?
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}node;
node *create(int n)
{
node *p=NULL,*head;
head=(node*)malloc(sizeof(node));
p=head;
node *s;
int i=1;
if(n!=0)
{
while(i<=n)
{
s=(node *)malloc(sizeof(node));
s->data=i++;
p->next=s;
p=s;
}
s->next=head->next;
}
free(head);
return s->next;
}
int main()
{
int n=41;
int m=3;
int i;
node *p=create(n);
node *temp;
m%=n;
while(p!=p->next)
{
for(i=1;i<m-1;i++)
{
p=p->next;
}
printf("%d->",p->next->data);
temp=p->next;
p->next=temp->next;
free(temp);
p=p->next;
}
printf("%d\n",p->data);
return 0;
}
展开
 我来答
紫荆c
2013-10-18
知道答主
回答量:20
采纳率:0%
帮助的人:20.7万
展开全部
#include<stdio.h>
#include<stdlib.h>
typedef struct node

 int data; 
 struct node *next;
}node;
 node *create(int n)
 { 
  node *p=NULL,*head; 
  head=(node*)malloc(sizeof(node)); 
  p=head; 
  node *s; 
  int i=1; 
  if(n!=0) 
  {  
   while(i<=n)  
   {   
    s=(node *)malloc(sizeof(node));   
    s->data=i++;   
    p->next=s;   
    p=s;  
   }  
   s->next=head->next; //创建一个无头结点单循环链表
  } 
  free(head);  
  return s->next;
 }
int main()

 int n=41; 
 int m=3; 
 int i; 
 node *p=create(n); 
 node *temp; 
 m%=n;//等价于 m=m%n,m比n小取余也是m 
 printf("依次出列的序号为:\n");
 while(p!=p->next) 
 {  
  for(i=1;i<m-1;i++)//报数1到2,指针停留在2  
  {   
   p=p->next;  
  }
  
  printf("%d ",p->next->data); //输出第3个数 
  temp=p->next;  
  p->next=temp->next; //从链表中释放被删除的结点 
  free(temp);  
  p=p->next;//结点p移至下一轮的1 
 }
 printf("\n最后留下的人的序号是:");
 printf("%d\n",p->data); 
 return 0;
}

/*程序的代码没有什么问题,可能是你看不懂吧,再者就是输出不好看,我改了一下,应该清晰

*多了

*/

 

推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式