#include <iostream>
using namespace std;
typedef enum{OK,ERROR,TURE,FLASE}Status;
typedef struct StackNode
{
//栈节点数据
int data;
//栈的指针 指向下一个节点
struct StackNode* next;
}StackNode,*LinkStack;
//链栈初始化
Status InitStack(LinkStack& S)
{
//构造一个空栈,栈顶指针置空
S = NULL;
return OK;
}
//入栈
Status Push(LinkStack& S,int e)
{
StackNode *P;
P = new StackNode;
P->data = e;
P->next = S;
S = P;
return OK;
}
//取栈长度
Status StackLength(LinkStack& S,int& length)
{
//栈非空
if(S == NULL)return ERROR;
StackNode *p;
p = S;
while(p != NULL)
{
length++;
p = p->next;
}
return OK;
}
//
Status GetTop(LinkStack& S,int& e)
{
if(S == NULL)return ERROR;
e = S->data;
return OK;
}
//出栈
Status Pop(LinkStack& S,int& e)
{
//若栈不空,则删除栈顶元素,用e返回,并返回OK,否则返回ERROR
if(S==NULL)return ERROR;
e = S->data;
StackNode *P;
P = S;
S = S->next;
delete P;
return OK;
}
//遍历 栈
Status StackTraverse(LinkStack& S)
{
if(S == NULL)return ERROR;
StackNode *p = S;
while(p != NULL)
{
cout<<p->data<<" ";
p = p->next;
}
return OK;
}
//清空栈
Status ClearStack(LinkStack& S)
{
if(S == NULL)return ERROR;
StackNode *p;
p = S;
while(p != NULL)
{
p->data = 0;
p = p->next;
}
return OK;
}
//判断栈是否为空
Status StackEmpty(LinkStack& S)
{
if(S == NULL)return FLASE;
else
return TURE;
}
//销毁
Status DestroyStack(LinkStack& S)
{
StackNode *p;
p = S;
while(p != NULL)
{
S = S->next;
delete p;
p = S;
}
return OK;
}
int main()
{
Status Sta;
LinkStack S;
InitStack(S);
int e;
cout<<"输入数据,数据以-1结束!"<<endl<<endl;
cout<<"输入数据: ";
while(cin>>e,e!=-1)
{
Push(S,e);
}
int length = 0;
StackLength(S,length);
cout<<"栈的长度 : "<<length<<endl;
cout<<"遍历栈:";
StackTraverse(S);
cout<<endl;
GetTop(S,e);
cout<<"栈顶元素: "<<e<<endl;
cout<<"数据出栈: ";
while(TURE == StackEmpty(S))
{
Pop(S,e);
cout<<e<<" ";
}
Sta = DestroyStack(S);
if(Sta == OK)cout<<endl<<endl<<"销毁成功"<<endl;
cout<<endl;
return 0;
}