头文件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");
}onemoo
相关分类