坑点
在运行Joseph函数的时候,我们的初始条件当编号为1
的时候循环是不执行的,就会导致编号为1的下一个元素出问题。
!!果然考虑问题,1,0这种边缘量应该单独考虑。
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#define N 9
#define OVERFLOW 0
#define OK 1
typedef struct LNode
{
int keyword;
struct LNode * next;
}LNode,*LinkList;
int *key[N] = {4,7,5,9,3,2,6,1,8};
void Joseph(LinkList p, int m, int x);
void Joseph(LinkList p, int m, int x)
{
if(x == 0) return;
LinkList q = p; //single list delete element need prior point and last point;
if(m == 1) p = p->next;
for(int i=1; i<m; i++) //由于q = p , p = p -> next;是初始条件,但是当m=1时,这个初始条件是不能运行的;
{
q = p;
p = p->next; //p is the key;
}
printf("%d ",p->keyword);
q->next = p->next;
int temp = p->keyword;
if(temp != 1) q = q->next;
free(p);
Joseph(q,temp,x-1);
}
int main()
{
int i,m;
LinkList Lhead, p, q, front;
p = (LNode*)malloc(sizeof(LNode));
printf("please input the start number:");
scanf("%d", &m);
for(i=0; i<N; ++i)
{
q = (struct LNode*)malloc(sizeof(LNode));
q->keyword = key[i];
if(i == 0)
{
p = q;
front = q;
}
else
{
p->next = q;
p = q;
}
if(key[i] == m) Lhead = q;
}
p->next = front;
printf("the output alignment is:\n");
Joseph(Lhead,m,N);
return 0;
}