帮我看看奇怪的错误
题目是:若干个人(在下面的程序中人数是people_sum,由用户输入)围成一圈,每个人有一个编号(从1到people_sum)。从第一个人开始报数,数到某个固定的数(在下面程序中为用宏定义的NUM_TO_OUT)时,此人就退出圈外,然后下一个人右从1开始报数,数到那个固定的数的人又退出……周而复始,直到只剩下一个人,要求打印出最后那个人的号数 。问题:下面我给出的程序的运行结果经过若干次测试都是正确的,但是如果将我注释的“怪事就在这里出现的”那段程序改成:
if(counter%NUM_TO_OUT == 0)//数到三时就移除结点(让该人退出圈外)
{
current = current->next;
front->next = current;
}
结果就会出错。真是让我百思不得其解!!请高手指点迷津……
#include <stdio.h>
#include <malloc.h>
#define NUM_TO_OUT 3
typedef struct S_PEOPLE
{
int number;
struct S_PEOPLE *next;
}S_PEOPLE;
int main(int argc,char *argv[])
{
S_PEOPLE *head = NewNode();
S_PEOPLE *current = head;
S_PEOPLE *front = head;
int people_sum;
int i = 0;
int counter = 1;
printf("please input the sum of people:\n");
scanf("%d",&people_sum);
head->number = 1;
for(i=1; i<people_sum; i++)
{
current->next = NewNode();
current = current->next;
current->number = i+1;//为每个结点编一个号码
}
current->next = head;//使首尾相连
current = front->next;
while(current->number != front->number)
{
counter++;
/********************怪事就在这里出现********************/
if(counter%NUM_TO_OUT == 0)//数到三时就移除结点(让该人退出圈外)
{
RemoveNode(front,current);
}
/********************************************************/
front = current;
current = current->next;
}
printf("the last people is number %d\n",current->number);//打印最后出圈的那个人的号数
return 0;
}
S_PEOPLE *NewNode(void)
{
S_PEOPLE *node = (S_PEOPLE *)malloc(sizeof(S_PEOPLE));
return node;
}
void RemoveNode(S_PEOPLE *front, S_PEOPLE *current)//移除结点
{
current = current->next;
front->next = current;
}