用单循环链表解决约瑟夫环问题,程序异常终止
如图,运行时程序会直接报错中止,我看了很久,一点问题没看出来。。。求各位指点一下编译环境:VS2017
代码:
#include"stdio.h"
#include"stdlib.h"
typedef struct LNode
{
int data;
struct LNode *next;
}LNode, *LinkList;
LinkList creat()
{
LinkList rear, head, p;
head = rear = (LinkList)malloc(sizeof(LNode));
rear->next = head;
printf("请输入所需长度n\n");
int n;
scanf("%d", &n);
int i;
for (i=1;i<n;i++);
{
p = (LinkList)malloc(sizeof(LinkList));
p->data = i;
p->next=rear->next;
rear->next=p;
rear=p;
}
rear->next->data=n;
return head;
}
int Delete(LinkList head, int i)//本行i指报数的几
{
LinkList p = head;
LinkList q = head->next;
int j = 1;
while (p->next !=p)
{
if (j == i)
{
p->next = q->next;
printf("%d\n",q->data);
free(q);
q=p->next;
j=1;
}
p=q;
q=q->next;
j=j++;
}
return (p->data);
}
int main()
{
LinkList L;
L = creat();
printf("%d",Delete(L,3));
return 0;
}