Chinaunix
标题:
C++栈的链表实现,编译通过,运行时报错,求指点
[打印本页]
作者:
zmy235
时间:
2014-04-03 21:36
标题:
C++栈的链表实现,编译通过,运行时报错,求指点
本帖最后由 zmy235 于 2014-04-13 10:11 编辑
#include <iostream>
using namespace std;
typedef int T;
class Node
{
private:
T data;
Node * link;
public:
Node()
{
link = NULL;
}
Node(T x)
{
data = x;
link = NULL;
}
friend class List;
};
class List
{
private:
Node *first;
public:
void push(const T x)
{
Node * newnode = new Node(x);
newnode->link = first->link;
first->link = newnode;
}
void pop()
{
Node * current = first->link;
first->link = current->link;
delete []current;
}
void output()
{
Node * current = first->link;
if(current->link!=NULL)
{
cout<<current->data<<"--"<<endl;
current = current->link;
}
else
{
cout<<current->data<<endl;
}
}
};
int main()
{
List list;
int x;
while(cin>>x)
list.push(x);
list.output();
return 0;
}
复制代码
作者:
Herowinter
时间:
2014-04-03 22:23
回复
1#
zmy235
试了下,我运行时没报错。
(gdb) run
Starting program: /sandbox/test
111
222
333
333--
Program exited normally.
复制代码
作者:
libo26_lee
时间:
2014-04-04 08:37
本帖最后由 libo26_lee 于 2014-04-04 08:37 编辑
List没有显式初始化函数,push操作时 newnode->link = first->link; 但是first没有初始化。。。
作者:
bskay
时间:
2014-04-07 11:05
用std就别造轮子了,要造,也搞个泛型模版的吧
作者:
tansijie
时间:
2014-04-07 22:13
运行时 报什么错, 是不是coredump了。如果coredump了就看下堆栈,或者加调试语句, 我光就2个类的实现来看,的确没看出任何毛病,有可能cin 那块是不是有问题。
作者:
zmy235
时间:
2014-04-10 15:22
回复
3#
libo26_lee
o,这个问题。
作者:
zmy235
时间:
2014-04-10 15:29
本帖最后由 zmy235 于 2014-04-10 16:32 编辑
回复
3#
libo26_lee
你说的对
作者:
zmy235
时间:
2014-04-10 15:32
回复
4#
bskay
你说的对,用个模板更合适
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2