在s_go()函数中发生了错误。
进入循环前,array指向的值是正确的。但是,进入循环后,array指向的值发生了变化。
约瑟夫问题。
#include /*约瑟夫问题*/
#include
struct node {
int no;
struct node *next;
};
// 生成循环链表
struct node *o_circle(int n) {
int i;
struct node *head, *p, *p1, *q;
head = p1 = (struct node *)malloc(sizeof(struct node));
p1->no = 1;
for ( i=2; i1; i++ ) { /* 生成循环链表 */
p = (struct node *)malloc(sizeof(struct node));
p1->next = p;
p->no = i;
p1 = p;
}
p1->next = head; /* p1(第30个) 指向开头head,形成循环 */
return head;
}
// 剔除节点
int *del(struct node *head,int n,int m) {
int i,k,array[n];
struct node *q;
for ( i=0; ifor (k=1;k-1;k++)
head = head->next; /* 找到第8(m-1)个 */
q = head->next; /* q为第9(m)个 */
head->next = q->next; /* 循环链表跳过要出列的结点 */
head = q->next; /* 下一轮,重新数数 */
array[i] = q->no; /* 将节点存进数组 */
printf("%d,",array[i]);
free(q); /* 释放 q 结点 */
}
printf("\n");
return array;
}
// 调整顺序,从第s个数开始
void s_go(int *array,int n,int s) {
int i,j;
printf("\n\n%d\n\n",array[15]); // 这一步array的值还是正确的
for (i=0;iprintf("%d,",array[i]); // 到了这一步就发生了错误
// if ( array[i]-s+1 > 0 )
// printf("%d,",array[i]-s+1);
// else
// printf("%d,",array[i]);
}
}
// main
int main() {
int n=30,s=1,m=9;
struct node *head;
int *p;
// scanf("%d,%d,%d",&n,&s,&m);
head = o_circle(n);
p = del(head,n,m);
s_go(p,n,s);
return 0;
}
口E:C语言约瑟夫问题求解.ex6 口 X
9.18.27,6,16.26.7,19,30,12,24,8,22,5,23,11,29,17,10,2,28,25,1,4,15,13,14,3,20,21,
11
1174996432,32761,-1174996432,32761,6487464,0,-1174996432,32761,6,0,-1175286805,32761,1,0,-1174996432,32761,1,0,-1174996
432.32761.28.25,1,4,11735888,0,28,0,1,0
Processexited after0.03085seconds withreturn value0
青按任意键继续
“Devil组”引证GPT后的撰写: