约瑟夫环问题
#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
int num,password;
struct Node *next;
}NODE;
NODE *createlink(int n);
int main( ){
int m,n,i;
NODE *head=NULL,*p1,*p,*q;
printf("请输入上限m人数n");
scanf("%d%d",&m,&n);
head=createlink(n);
q=head;
for(i=1;i<=n;i++){
printf("请输入第%d个人的密码",i);
scanf("%d",&q->password);
q->num=i;
q=q->next;
}
p=head;
while(p->next->next){
if(p->next->password==m){
printf("%d",p->next->num);
m=p->next->password;
p1=p->next;
p->next=p1->next;
free(p1);
}
p=p->next;
}
system("pause");
return 0;
}
NODE *createlink(int n){
NODE *head=NULL,*p=NULL,*q=NULL;
int i=1;
head=p=(struct Node*)malloc(sizeof(struct Node));
if(!head){
printf("分配内存失败");
exit(-1);
}
for(i=2;i<=n;i++){
q=(struct Node*)malloc(sizeof(struct Node));
if(q==0) return 0;
p->next=q;
p=q;
}
p->next=head;
return head;
}
输完每个人的密码后程序就不往下运行了,高手帮我解决下
[解决办法]
你这个函数错误很多,慢慢单步跟踪下吧。提点建议,定义一个数据一定要对其初始化,尤其在动态开辟一个节点时,q->next=NULL;要不你后面的循环可能结束不了的。
[解决办法]
http://blog.csdn.net/hondely/article/details/6930548