#include <iostream>
using namespace std;
typedef int StackElemType;
typedef struct Node
{
StackElemType data;
struct Node *next;
}StackNode,*LinkStack;
void InitStack(LinkStack &top);
int StackEmpty(LinkStack top);
void Push(LinkStack top,StackElemType e);
void Pop(LinkStack top,StackElemType &e);
StackElemType GetTop(LinkStack top);
void PrintStack(LinkStack top);
void InputStack(LinkStack top);
int main(int argc, char const *argv[])
{
LinkStack stack;
InitStack(stack);
InputStack(stack);
PrintStack(stack);
int x;
Pop(stack,x);
cout<<"top:"<<GetTop(stack)<<endl;
Pop(stack,x);
cout<<"top:"<<GetTop(stack)<<endl;
PrintStack(stack);
return 0;
}
void InitStack(LinkStack &top)
{
top = new StackNode;
top->next = NULL;
}
int StackEmpty(LinkStack top)
{
return top->next == NULL;
}
void Push(LinkStack top,StackElemType x)
{
StackNode *s = new StackNode;
s->data = x;
s->next = top->next;
top->next = s;
}
void Pop(LinkStack top,StackElemType &e)
{
LinkStack s;
s = top->next;
if(s == NULL)
cout<<"The stack is empty"<<endl;
top->next = s->next;
e = s->data;
delete s;
}
void InputStack(LinkStack top)
{
cout<<"请输入一组元素,以-1结束:";
int m;
cin>>m;
while(m!=-1)
{
Push(top,m);
cin>>m;
}
}
StackElemType GetTop(LinkStack top)
{
if(StackEmpty(top))
cout<<"The stack is empty!"<<endl;
return top->next->data;
}
void PrintStack(LinkStack top)
{
if(top->next == NULL)
cout<<"The stack is empty"<<endl;
else
{
while(top->next)
{
cout<<top->next->data<<" ";
top = top->next;
}
}
cout<<endl;
}
链栈
最新推荐文章于 2022-09-15 18:14:04 发布