注册 登录
编程论坛 C++教室

[求助]单链表册除问题-->yms123转移

lzq_wise1 发布于 2007-05-16 15:43, 564 次点击

程序源代源如如下:
#include<iostream.h>
struct node
{
int data;
node *next;
};
class josephus
{
public:
josephus()
{
first=new node;
first->next=NULL;
}
josephus(int a[],int n);
~josephus(); //析构函数
void Delete(int i);
void print();
private:
node *first;
};
josephus::josephus(int a[],int n) //头播法建立单链表
{
first=new node;
first->next=NULL;
for(int i=0;i<n;i++)
{
node *s;
s=new node;
s->data=a[i];
s->next=first->next;
first->next=s;
}
}
josephus::~josephus()
{
node *p;
node *q;
p=first->next;
while(p)
{
q=p;
p=p->next;
delete q;
}

}
void josephus::Delete(int i)
{
node *p;
p=new node;
p=first;
int j=0;
int x=0;
while(p&&j<i-1)
{
p=p->next;
j++;
}
if(!p||!p->next) throw "位置";
else
{
node *q;
q=new node;
q=p->next;
x=q->data;
p->next=q->next;
//cout<<x;
delete q;
//return x;
}
}
void josephus::print()
{
node *s;
s=new node;
s=first->next;
while(s)
{
cout<<s->data<<endl;
s=s->next;
}
}

void main()
{
int *p,m,n;
cout<<"请输入总人数"<<endl;
cin>>m;
p=new int[m];
for(int i=0;i<m;i++)
p[i]=i;
josephus();
josephus t(p,m);
~josephus(); //此处的析构函数在编译时提示前面的符号不能识别
t.print();
cout<<"请输入第一个出队的人的位置"<<endl;
cin>>n;
cout<<"出队的顺序为"<<endl;
for(int j=0;j<m;j++) //按位册除 ??此处我用了一个for循环为什么就不行了呢?请高手指教
t.Delete(n);
}

5 回复
#2
ming2062007-05-16 15:52
有什么错误提示呢?C++好久没看了。觉得
for(int j=0;j<m;j++) t.Delete(n); 这里不行。指针找不到对应位置。
#3
lzq_wise12007-05-20 22:58

我就是想用一个for循环删除整个链表,是不是非要用个单循环链表才行呢?
谢谢楼上的解答

#4
yms1232007-05-20 23:00
还是帮楼主转C++版块那里的版主应该能解决楼主的问题。
#5
aipb20072007-05-21 09:57

楼主,你的错误有点多呢,最主要的,你每次声明一个指针,你都会为它分配动态内存,有几个地方没用到也没释放,直接内存泄露。

还有就是你那个按位删除,问题不小,缴去缴来,不知道楼主自己是否清晰思路?反正读起来很费力。

还有,析构函数不需要显示调用。

建议楼主自己理理思路先。

#6
lzq_wise12007-05-22 19:01

版主辛苦了,这个问题基本上解决了,谢谢楼上各位仁兄的见解

1