#include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct StackNode
{
char data;
struct StackNode *next;
} *LinkStack;
void InitStack(LinkStack &S)
{
S = NULL;
}
bool StackEmpty(LinkStack &S)
{
if (S == NULL)
return true;
else
return false;
}
char GetTop(LinkStack &S)
{
if (S==NULL){
cout<<"栈已为空";
exit(0);
}
else
return S->data;
}
int Push(LinkStack &S, char &e)
{
StackNode *p = new StackNode;
p->data=e;
p->next=S;
S=p;
return 1;
}
int Pop(LinkStack &S, char &e)
{
if (S == NULL)
return 0;
e = S->data;
StackNode *p = new StackNode;
p=S;
S=S->next;
delete p;
return 1;
}
void StackTraverse(LinkStack &S)
{
StackNode *p = S;
while (p != NULL)
{
cout<<p->data;
p=p->next;
}
delete p;
}
int main()
{
LinkStack S;
char e;int i,n ;
InitStack(S);
cout<<"输入栈的长度:";
cin>>n;
cout<<"输入栈的元素:";
for (i = 1; i <= n; i++)
{
cin>>e;
Push(S,e);
}
cout<<"遍历输出栈中的所有元素:";
StackTraverse(S);
cout<<endl<<"请输入要插入的元素的数值:";
cin>>e;
Push(S,e);
cout<<"栈顶元素是:"<<GetTop(S)<<endl;
cout << "依次弹出的队头元素为:";
while (Pop(S, e)) {
cout << e << " ";
}
if (StackEmpty(S))
cout<<endl<<"栈为空";
else
cout<<endl<<"栈非空";
return 0;
}