#include typedef int ElemType;
typedef struct node
{
ElemType data;
struct node*next;
}*linkStack,stackNode;
//链栈初始化
linkStack initLinkStack()
{
linkStack top=(linkStack)malloc(sizeof(stackNode));
if(!top)
{
printf("动态内存分配失败!\n");
exit(0);
}
else
{
top->next=NULL;
printf("链栈初始化成功!\n");
return top;
}
}
//入栈
int push(linkStack top,ElemType e)
{
if(top)
{
linkStack p=(linkStack)malloc(sizeof(stackNode));
p->data=e;
p->next=top->next;
top->next=p;
return 1;
}
return 0;
}
//出栈
int pop(linkStack top,ElemType *e)
{
if(top->next)
{
linkStack p=top->next;
*e=top->next->data;
top->next=p->next;
return 1;
}
return 0;
}
//判断栈空
int isEmpty(linkStack top)
{
if(top->next==NULL)
return 1;
return 0;
}
//获取栈顶元素
int getTop(linkStack top)
{
if(top->next)
{
return top->next->data;
}
return -1;
}
int main()
{
linkStack top=initLinkStack();
if(isEmpty(top))
{
printf("当前栈为空!\n");
}
int n,a[100],i,t,elemT;
printf("请输入数字n\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
push(top,a[i]);
elemT=getTop(top);
/* if(elemT!=-1)
{
printf("当前栈顶元素为%d\n",elemT);
}*/
}
while(top->next)
{
pop(top,&t);
printf("%d ",t);
elemT=getTop(top);
/* if(elemT!=-1)
{
printf("当前栈顶元素为%d\n",elemT);
}*/
}
if(isEmpty(top))
{
printf("当前栈为空\n");
}
return 0;
}