
关于约瑟夫环的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;
} 展开
#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;
} 展开
1个回答
展开全部
#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;
}
/*程序的代码没有什么问题,可能是你看不懂吧,再者就是输出不好看,我改了一下,应该清晰
*多了
*/
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询