当前位置: 代码迷 >> C语言 >> C的约瑟夫环问题,有2个问题不懂,请指点.
  详细解决方案

C的约瑟夫环问题,有2个问题不懂,请指点.

热度:247   发布时间:2006-10-23 22:27:32.0
C的约瑟夫环问题,有2个问题不懂,请指点.

以下程序是朋友帮写的,编译测试是正确的,可有2个问题(已加粗)不明白.
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int *Array;
int t,n,m,i,j,k,x;

struct jose { int data;
int numth;
struct jose *next;
}Node;

struct jose *head,*q,*p,*tempe,*temp,*T;

head = NULL;
printf("Input the number of people:\n");
scanf("%d",&n);
Array = (int*)malloc(sizeof(int) * n );
for( i = 0; i < n; i++)
{ scanf("%d\n",&Array[i]);
if (!head){
head = (struct jose*)malloc( sizeof(*head));
p = head;
p -> data = Array[i];
p -> numth = i + 1;
p -> next = head ;
}
else{
q = (struct jose*)malloc( sizeof(*q));
q -> data = Array[i];
q -> numth = i + 1;
q -> next = p -> next;
p -> next = q;
p = q;
}
};

printf("Input the code-num(o<=m<=20):\n");

do{
scanf("%d",&m);
}while(m<0||m>20);

tempe = p;
for (t = 0 ;t < n;t++)
{ for (j = 1;j < m;j++)
tempe = tempe -> next;


printf("%d",tempe -> next -> numth);

m = tempe -> next-> data;
T = tempe -> next;
tempe -> next = T ->next;
free(T);

}
}

第一个printf应该是在输入M以前出现,为什么编译后是在输入M后出现?

第二个:本身此时循环链表的P是指向最后输入的结点的,而for语句为什么是从后往前数了m-1位?

搜索更多相关的解决方案: 约瑟夫  

----------------解决方案--------------------------------------------------------
  相关解决方案