#include<iostream>
using namespace std;
typedef float datatype;
struct node //节点类型定义
{
datatype data;
struct node *next;
};
class linkstack //栈结构定义
{
public:
linkstack(){top=NULL;} //构造函数,初始化一个空链栈
~linkstack(); //析构函数,释放链栈中各结点的储存空间
void push(datatype x); //入栈操作,将元素x入栈
datatype pop(); //出栈操作,将栈顶元素出栈
datatype getpop(); //取栈顶元素(并不删除)
bool IsEmpty(){return (NULL==top)?true:false;} //判空操作,判断链栈是否为空栈,栈空则返回1,栈非空则返回0
private:
struct node *top; //栈顶指针即链栈的头指针
};
linkstack::~linkstack()
{
while(top)
{
node *p=top; //暂存被释放的结点
top = top->next; //top指向被释放结点的下一个结点
delete p;
}
}
void linkstack::push(datatype x)
{
node *p=new node; //申请一个数据域为x的结点
p->data=x;
p->next = top; //将节点插在栈顶
top=p;
}
datatype linkstack::pop()
{
if (IsEmpty()) throw "下溢";
datatype x=top->data; //暂存栈顶元素
node *p=top;
top=top->next; //将栈顶结点摘链
delete p;
return x;
}
datatype linkstack::getpop()
{
if(top!=NULL)
return top->data; //返回栈顶指针top所指结点的数据域
else
cout<<"Stack is Empty !"<<endl;
}
int main()
{
linkstack mystack;
cout <<"Is stack Empty:" << mystack.IsEmpty() << endl;
for(int i = 0;i < 10;i++)
{
mystack.push(i);
cout<<i<<endl;
}
cout <<"Is stack Empty:" << mystack.IsEmpty() << endl;
for(int i=0;i<10;i++){
cout <<"The top of the stack is :" << mystack.getpop() << endl;
mystack.pop();
}
cout <<"Is stack Empty:" << mystack.IsEmpty() << endl;
system("pause");
return 0;
}
运行结果: