Code

/*链表实现栈的一系列操作*/
#include
#include
#define OK 1
#define ERROR 0
typedef struct node
{
int data;
struct node *next;
}LinkStackNode,*LinkStack;
/**********************各个子函数的定义*********************/
void initStack(LinkStack *top); //初始化链栈
int push(LinkStack top,int n); //链栈进栈操作
void pop(LinkStack top); //链栈出栈操作
int getTop(LinkStack top,int *s); //读取链栈栈顶元素
int main()
{
LinkStack top;
int choice;
while(true)
{
printf("*****************Please enter your choice*****************\n\n");
printf(" choice 1:Stack initialization\n");
printf(" choice 2:Into the stack\n");
printf(" choice 3:Out of the stack\n");
printf(" choice 4:Read the stack elements\n");
printf(" choice 0:exit\n\n");
scanf("%d",&choice);
switch(choice)
{
case :
initStack(&top);
break;
case :
int n;
printf("Please enter the number into the stack elements:");
scanf("%d",&n);
(push(top,n)==)?printf("%d个元素依次进栈成功\n",n):printf("%d个元素依次进栈失败\n",n);
break;
case :
pop(top);
break;
case :
int* s;
(getTop(top,s)==)? printf("栈顶元素是:%d.\n",*s):printf("An empty stack error!!!!\n"); //三目运算符
break;
case :
exit();
break;
default:
printf("ERROR!!\n");
exit();
break;
}
}
return ;
}
/**********************各个子函数功能的实现*********************/
void initStack(LinkStack *top)
{ //初始化
*top=(LinkStack)malloc(sizeof(LinkStackNode)); //带头结点的单链表
(*top)->next=NULL;
}
int push(LinkStack top,int n) //进栈 ,将元素压入栈中
{
LinkStackNode *temp;
int n1,n2;
printf("Please enter into the stack elements in turn:\n");
for(n1=;n1
{
scanf("%d",&n2);
temp=(LinkStackNode *)malloc(sizeof(LinkStackNode)); //结点申请空间
if(temp==NULL) return ERROR; //申请空间失败
temp->data=n2;
temp->next=top->next; //采用头插法存储元素
top->next=temp;
}
return OK;
}
void pop(LinkStack top) //栈顶元素出栈
{
int a;
LinkStackNode *temp;
if(top->next==NULL)
{ //栈为空,出栈失败
printf("An empty stack error!!!!\n");
}
else
{
temp=top->next;
a=temp->data;
top->next=temp->next;
free(temp);
printf("栈顶元素%d出栈成功.\n",a);
}
}
int getTop(LinkStack top,int *s) //获读取栈顶元素
{
if(top->next==NULL) //栈为空,读取栈顶元素失败
{
return ERROR;
}
else
{
*s=(top->next)->data; //读取栈顶元素,不出栈
return OK;
}
}