C++循环链表的问题(约色夫生死游戏)

来源:百度知道 编辑:UC知道 时间:2024/06/22 22:20:06
#include <iostream.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#include <stdio.h>

typedef struct list
{
int num;
struct list *next;
} node;

list create(int i)
{
list l;
list *s;
l.next=&l;
while(i>0)
{
s=new list;
s->num=i;
s->next=l.next;
l.next=s;
i--;
}
return l;
}

void main()
{
int people,np,n,i;
list p,*t;
cout<<"输入总人数";
cin>>people;
cout<<"报数上限(1-"<<people/2<<"):";
cin>>n;
p=create(people);
t=&p;
np=people;
cout<<"位置"<<endl;
while(np!=(people/2))
{
i=n;
while(i-->1)t=t->next;
cout<<t->next->num<<endl;
t->next=t->next->next;
np--;

问题在这里:

list create(int i)
{
list l;
list *s;
l.next=&l;
while(i>0)
{
s=new list;
s->num=i;
s->next=l.next;
l.next=s;
i--;
}
return l;
}

这里你是把为指针指向头节点了(那个 l),但是那个 l 是个临时变量,
这个程序结束后,它就没有了.返回时返回了一个副本.
但是这个副本的地址跟那个l已经不一样了
而你的尾指针指向的还是以前程序里面那个已经不存在的临时变量l

可以这样改一下:
list &create(int i)
{
list &l=*(new list);
list *s;
l.next=&l;
while(i>0)
{
s=new list;
s->num=i;
s->next=l.next;
l.next=s;
i--;
}
return l;
}

另外你的new申请的内存没有delete,这样会造成内存丢失.
需要写一个函数把整个链表删除