Chinaunix

标题: C++栈的链表实现,编译通过,运行时报错,求指点 [打印本页]

作者: zmy235    时间: 2014-04-03 21:36
标题: C++栈的链表实现,编译通过,运行时报错,求指点
本帖最后由 zmy235 于 2014-04-13 10:11 编辑
  1. #include <iostream>
  2. using namespace std;
  3. typedef  int T;

  4. class Node
  5. {
  6. private:
  7.     T data;
  8.     Node * link;

  9. public:
  10.     Node()
  11.     {
  12.         link = NULL;
  13.     }   
  14.     Node(T x)
  15.     {
  16.         data = x;
  17.         link = NULL;
  18.     }
  19.     friend class List;

  20. };

  21. class List
  22. {
  23. private:
  24.     Node *first;

  25. public:
  26.     void push(const T x)
  27.     {
  28.         Node * newnode = new Node(x);
  29.         newnode->link = first->link;
  30.         first->link = newnode;
  31.     }
  32.     void pop()
  33.     {
  34.         Node * current = first->link;
  35.         first->link = current->link;
  36.         delete []current;
  37.     }
  38.     void output()
  39.     {
  40.         Node * current = first->link;
  41.         if(current->link!=NULL)
  42.         {
  43.             cout<<current->data<<"--"<<endl;
  44.             current = current->link;
  45.         }
  46.         else
  47.         {
  48.             cout<<current->data<<endl;
  49.         }
  50.     }
  51. };


  52. int main()
  53. {
  54.     List list;
  55.     int x;
  56.     while(cin>>x)
  57.         list.push(x);

  58.     list.output();
  59.     return 0;
  60. }
复制代码

作者: Herowinter    时间: 2014-04-03 22:23
回复 1# zmy235
试了下,我运行时没报错。
  1. (gdb) run
  2. Starting program: /sandbox/test
  3. 111
  4. 222
  5. 333
  6. 333--

  7. 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