#include<stdio.h> #include<stdlib.h> typedef struct stacknode/ { int data; struct stacknode *next; }stacknode,*linkstack; linkstack InitStack(linkstack s);//初始化 int empty(linkstack s); int Push(linkstack s,int e);//入栈 int Pop(linkstack s);//出栈 int gettop(linkstack s);//取栈顶元素 void print(linkstack s);//打印栈 int destroyStack(linkstack s); int main()
int main()
{
linkstack s;
int choice,data,e;
s=(linkstack )malloc(sizeof(linkstack));
s=InitStack(s);
while(1)
{
printf("请输入相应数字,选择操作:\n");
printf("1.入栈 2.出栈 3.打印 4.取栈顶元素 5.结束\n");
scanf("%d",&choice);
if(choice!=1&&choice!=2&&choice!=3&&choice!=4&&choice!=5)
{
printf("非法选择!请重新选择:\n");
scanf("%d",&choice);
}
if(choice==1)
{
printf("请输入一个要入栈的数据:");
scanf("%d",&data);
e=data;
Push(s,e);
}
if(choice==2)
{
if(!empty(s))
Pop(s);
else
printf("这是一个空栈!\n");
}
if(choice==3)
{
if(!empty(s))
print(s);
else
printf("这是一个空栈!\n");
}
if(choice==4)
{
if(!empty(s))
gettop(s);
else
printf("这是一个空栈!\n");
}
if(choice==5)
return 0;
}
}
linkstack InitStack(linkstack s)//这里的s 是形参
{
s=(linkstack )malloc(sizeof(linkstack));
if (s == NULL)
printf("创建失败");
s->data = 0;
s->next=NULL;
return s;
}
int empty(linkstack s)
{
linkstack p;
p=s->next;
if(p== NULL)
return 1;
else return 0;
}
int Push(linkstack s,int e)
{
linkstack p;
p=(linkstack )malloc(sizeof(linkstack));
p->data=e;
p->next = s->next;
s->next = p;
printf(" %d已入栈\n",e);
return 1;
}
int Pop(linkstack s)
{
linkstack p;
p=(linkstack )malloc(sizeof(linkstack));
p = s->next;
if (!empty(s))
{
s->next = s->next->next;
printf(" %d 已出栈\n",p->data);
free(p);
//return 1;
}
return 0;
}
int gettop(linkstack s)
{
linkstack p;
p=s->next;
if(p!=NULL)
{
printf("栈顶元素为:");
printf("%d \n",p->data);
}
return p->data;
}
void print(linkstack s)
{
linkstack p;
p=s->next;
printf("栈为:\n");
printf(" top of stack\n");
while(p!=NULL)
{
printf("%8d \n",p->data);
p = p->next;
}
printf(" base of stack \n");
}
int destroyStack(linkstack s)
{
while (!empty(s))
{
Pop(s);
}
printf("栈已销毁!\n");
free(s);
return 0;
}