为了账号安全,请及时绑定邮箱和手机立即绑定

C++数据结构(链栈) 检查了好多遍,不明白错在哪

C++数据结构(链栈) 检查了好多遍,不明白错在哪

C++
爱3 2015-10-24 19:03:43
头文件LinkStack.h #ifndef LINKSTACK_H //如果没有定义该 头文件,就执行以下的(define),否则就直接endif(避免二次调用 #define LINKSTACK_H template<class DataType>        //模板类 class LinkStack                 //链栈定义 { public: LinkStack();                             //构造函数 ~LinkStack();               //析构函数 void Push(DataType x);                   //入栈,增加 DataType Pop();             //出栈,删除 DataType GetTop();                      //取栈顶元素,不删除 int Empty();                //判空 private: Node<DataType> *top         //栈顶指针 }; #endif 源文件LinkStack.cpp #include<iostream> using namespace std; #include "LinkStack.h"                             //包含头文件 template<class DataType> LinkStack<DataType>::LinkStack()                  // { top=NULL;                                     //栈顶指针初始化为空 } template<class DataType> LinkStack<DataType>::~LinkStack()                 //析构函数 { } template<class DataType> void LinkStack<DataType>::Push(DataType x) { s=new Node;   s->data=x;  //申请一个数据域为x的节点s,next指向 s->next=top;  top=s;  //将节点s插在栈顶 } template<class DataType> DataType LinkStack<DataType>::Pop()       { if(top==NULL) throw "下溢";                 // x=top->data; p=top; top=top->next; delete p; return x; } template<class DataType> DataType GetTop() { if(top!= NULL)                              //不删除 return top->data; } template<class DataType> int Empty() { top==NULL ? return 1:return 0; } 主函数文件LinkStackMain.cpp #include<iostream> using namespace std; #include"LinkStack.cpp" void main() { LinkStack<int> L;                           //实例化类对象 if(L.Empty()==1) //判空 cout<<"栈为空"<<endl; else cout<<"栈为非空"<<endl; L.Push(2);                                 //依次入栈 L.Push(3); cout<<"栈顶元素为:"<<L.GetTop()<<endl;    //取栈顶元素 //cout<<"出栈:"<<L.Pop()<<endl;    cout<<"出栈:"<<endl; L.Pop(); cout<<"栈顶元素为:"<<L.GetTop()<<endl;    //出栈一次,栈顶元素改变 system("pause"); }
查看完整描述

1 回答

?
onemoo

TA贡献883条经验 获得超454个赞

出了错误先看报的是什么错! 说说报错是什么?

目测就有几个问题:

  • LinkStackMain.cpp中你include了LinkStack.cpp文件,这直接就会引起重定义错误。永远不要include包含实现的.cpp文件!

  • 我没看到Node类型的定义

查看完整回答
反对 回复 2015-10-25
  • 1 回答
  • 0 关注
  • 1512 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信