由于栈只在栈顶操作,因此,通常不设头结点。
#include<bits/stdc++.h>
using namespace std;
typedef struct Node
{
int date;
struct Node *next;
}SNode,*StackList;
void InitStack(StackList &top)//链栈的初始化
{
top=NULL;
}
int EmptyStack(StackList top)//判空
{
if(top==NULL)
return 1;
else
return 0;
}
void Push(StackList &top,int x)//入栈
{
StackList p;
p=new SNode;
p->date=x;
p->next=top;
top=p;
}
int Pop(StackList &top)//出栈
{
StackList q;
int x;
x=top->date;
q=top;
top=top->next;
delete q;
return x;
}
int main()
{
StackList top;
InitStack(top);
int n,x;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>x;
Push(top,x);
}
while(!EmptyStack(top))
{
cout<<Pop(top)<<" ";
}
return 0;
}
输入:
5
1 2 3 4 5
输出:
5 4 3 2 1