/*
栈的实现与相关的操作
栈的特点后进先出(Last In First Out),有栈底和栈顶,元素只可以从栈顶放入,也只可以从栈顶拿出
Insert(s,n+1,x);
Delete(s,n);
*/
//链栈
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef int ElemType;
typedef int Status;
typedef struct StackNode{
ElemType data;
StackNode *next;//第n个元素指向第n-1个,往前指
}StackNode,*LinkStack;
Status InitStack(LinkStack &S){
S = NULL;
return 1;
}
Status Push(LinkStack &S,ElemType &e){
StackNode *q;//
q = (StackNode *)malloc(sizeof(StackNode));
q->data = e;
q->next = S;
S = q; //S指向栈顶元素
return 1;
}
Status Pop(LinkStack &S,ElemType &e){
StackNode *p;
if(S==NULL)return 0;
e = S->data;
p = S;
S = S->next;
free(p);
return 1;
}
ElemType GetTop(LinkStack &S){
if(S==NULL)return 0;
return S->data;
}
int main(){
LinkStack S;
ElemType e;
//初始化
InitStack(S);
printf("1为进栈,2为出栈,3为取栈顶元素,4为退出操作\n");
int n,x;
while(true){
printf("请输入需要执行的操作:\n");
scanf("%d",&n);
switch(n){ //进栈
case 1: printf("请输入需要进栈的个数:\n");
scanf("%d",&x);
printf("输入进栈数据:\n");
for(int i = 0;i < x;i++){
scanf("%d",&e);
Push(S,e);
}break;
case 2: //打印链栈中的数据
printf("请输入需要出栈的个数:\n");
scanf("%d",&x);
for(int i = 0;i<x&&S!=NULL;i++){
Pop(S,e);
printf("%d ",e);
}
printf("\n");
break;
case 3:if(S==NULL){
printf("栈已空\n");break;
}else{
printf("栈顶元素为%d ",GetTop(S));
}break;
case 4:exit(0);
}
}
return 0;
}