实现链栈各种基本运算

#include
#include
#include
typedef int ElemType;
typedef struct node
{
ElemType data;
struct node *next;
}Stacknode,*LinkStack;
void Init_LinkStack(LinkStack &s)
{
s=(Stacknode *)malloc(sizeof(Stacknode));
s->next=NULL;
}
ElemType StackEmpty(LinkStack s)
{return (s==NULL);}
void Push(LinkStack &s,ElemType e)
{
LinkStack p;
p=(Stacknode *)malloc(sizeof(Stacknode));
p->data=e;
p->next=s;
s=p;
}
int Pop(LinkStack &s,ElemType &e)
{
LinkStack p;
if(s==NULL) return 0;
p=s;
e=p->data;
s=p->next;
free(p);
return 1;
}
int Get_Top(LinkStack s,ElemType &e)
{
if(s==NULL) return 0;
e=s->data;
return 1;
}
void Display_LinkStack(LinkStack s)
{
LinkStack p=s;
while(p->next!=NULL)
{printf("M",p->data);p=p->next;}
printf("\n");
}
void main()
{
ElemType e;
LinkStack s;
int cord,x,y;
Init_LinkStack(s);
Push(s,1);Push(s,2);Push(s,3);Push(s,4);
printf("初始化\n依次进栈元素为 1 2 3 4:\n");
Display_LinkStack(s);
do
{
printf("      主菜单        \n");
printf("   1   入栈         \n");
printf("   2   出栈         \n");
printf("   3   读栈顶元素   \n");
printf("   4   结束程序     \n");
printf("--------------------------\n");
printf("请输入您选择的菜单号<1, 2, 3, 4>:\n");scanf("%d",&cord);
switch(cord)
{
case 1:
{
printf("请输入入栈元素!");scanf("%d",&x);
Push(s,x);printf("由栈顶到栈底元素为:");
Display_LinkStack(s);
}break;
case 2:
{
Pop(s,x);printf("出栈元素为:%d\n",x);
printf("由栈顶到栈底元素为:");Display_LinkStack(s);
}break;
case 3:
{Get_Top(s,x);printf("栈顶元素为:%d\n",x);}
break;
case 4:
{printf("程序运行结束!");exit(0);}
break;
default:
printf("输入有误!");
}
}while(cord<=4);
}

你可能感兴趣的:(2012)