为方便调试,简化问题为5个人
#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(struct peo)
struct peo
{
int num;
peo *next;
}peo;
int main()
{
struct peo *creat();
void result(struct peo *head);
result(creat());
}
struct peo *creat()
{
int n=5,i=0;
struct peo *head;
struct peo *p1,*p2;
head=NULL;
p1=p2=(struct peo *)malloc(LEN);
while(i<n)
{
i++;
p1->num=i;
if(i==1)head=p1;
else p2->next=p1;
p2=p1;
p1=(struct peo *)malloc(LEN);
}
p2->next=head;
return head;
}
void result(struct peo *head)
{
struct peo *del(struct peo *head,int num);
struct peo *p1=head;
int baoshu=0,rest=5;
while(rest!=1)
{
baoshu++;
if(baoshu==3)
{
baoshu=0;
head=del(head,p1->num);
rest--;
}
p1=p1->next;
}
printf("the rest is %d",p1->num);
}
struct peo *del(struct peo *head,int num)
{
struct peo *p1=head,*p2=head;
if(p1->num==num)
{
head=p1->next;
do//不能退出
{
p2=p2->next;
}while(p2->next==p1);
p2->next=head;
}
else
{
p1=(p1->next);
do
{
if(p1->num==num)
{
break;
}
else
{
p1=p1->next;
p2=p2->next;
}
}while(p1!=NULL);
p2->next=p1->next;
}
return head;
}
结果运行后发现程序没有任何输出,通过调试发现一直在do循环处循环,不能退出。
do //该段代码不能退出
{
p2=p2->next;
}while(p2->next==p1);
我创建了一个拥有5个节点的环形链表,通过遇到报数为3的节点就用del函数“删除”这个节点(将上一个节点链接到下一个节点,跳过该节点来实现删除功能),直到最后只剩下一个节点为止,输出该节点的编号num。
最后我将问题代码替换成while循环,且终止条件不变,发现循环能正常退出,且程序输出的结果是正确的
while (p2->next != p1)
{
p2 = p2->next;
}