请教:约瑟夫环(用循环链表写的,但输出有错误,大家帮忙看看)
这是我的代码(我输出的是人的编号):#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int password;
int sequence;
struct Node* next;
}Link;
Link* Creat(Link* head, int* sequence);
Link* Find(Link* head, int password);
Link* Delete(Link* head, Link* target);
int main()
{
int sequence = 0; //人的编号
int password = 0; //每人手中的密码
int* pSequence = &sequence;
Link* pHead = NULL;
Link* pTarget = NULL;
pHead = Creat(pHead,pSequence);
printf("Please input a password:");
scanf("%d",&password);
pTarget = Find(pHead,password);
printf("%d->",pTarget->sequence);
password = pTarget->password;
pHead = Delete(pHead,pTarget);
while (pHead != NULL)
{
pTarget = Find(pHead,password);
printf("%d->",pTarget->sequence);
password = pTarget->password;
pHead = Delete(pHead,pTarget);
}
return 0;
}
Link* Creat(Link* head, int* sequence)
{
Link* pNewNode = NULL;
Link* pIter = NULL;
int password = 0;
while (scanf("%d",&password) != EOF)
{
pNewNode = (Link*)malloc(sizeof(Link));
pNewNode->password = password;
pNewNode->next = NULL;
if (head == NULL)
{
head = pNewNode;
}
else
{
for (pIter=head; pIter->next!=NULL; pIter=pIter->next)
{
continue;
}
*sequence = *sequence + 1;
pIter->next = pNewNode;
pIter->sequence = *sequence;
}
}
pNewNode->next = head;
return head;
}
Link* Find(Link* head, int password)
{
int length = 1;
Link* pIter = NULL;
for (pIter=head; length!=password; pIter=pIter->next)
{
length++;
}
length = 0;
return pIter;
}
Link* Delete(Link* head, Link* target)
{
Link* pIter = NULL;
for (pIter=head; pIter->next!=target; pIter=pIter->next)
{
continue;
}
if (target->next == pIter)
{
printf("%d\n",target->sequence);
head = NULL;
}
else
{
pIter->next = target->next;
head = target->next;
}
free(target);
return head;
}