#include<stdio.h>
#include<stdlib.h>
//#define NULL 0
#define MAXSIZE 1024 /*顺序表可能的最大长度,假设为1024 */
typedef int elemtype; /*elemtype可为任意类型,假设为int型 */
typedef struct LinkedStackNode
{
elemtype data; /*定义顺序表为一维数组*/
struct LinkedStackNode * next;
}LinkedStackNode,*LinkedStack;
LinkedStack top;
LinkedStack Init_LinkedStack();
int LinkedStack_Empty(LinkedStack top);
int Push_LinkedStack(LinkedStack top,elemtype x);
int Pop_LinkedStack(LinkedStack top,elemtype * x);
int GetTop_LinkedStack(LinkedStack top,elemtype * x);
void shuchu(LinkedStack top);
void menu();
int main()
{
char cmd;
int n,m,len,isdo;
LinkedStack top;
elemtype x;
system("cls");
menu();
while((cmd=getchar())!='#')
{ switch(cmd)
{ case '1': top=Init_LinkedStack();
if(top==NULL)
{
printf("申请链栈内存空间失败,程序结束");
return 0;
}
printf("\nCreatied the list!\n");
printf("\n\n\n\t\t\t");
break;
case '2':
printf("输入链栈元素:\n");
scanf("%d",&x);
while(x!=0)
{
isdo= Push_LinkedStack(top,x);
scanf("%d",&x);
}
if(isdo==1)
{
printf("插入成功");
}
else
{
printf("插入失败");
}
printf("\n");
printf("\n\n\n\t\t\t");
break;
case '3':
isdo=Pop_LinkedStack(top,&x);
if(isdo==0)
{
printf("删除失败");
}
else
{
printf("删除成功");
printf("栈顶元素为 %4d",x);
}
printf("\n\n\n\t\t\t");
break;
case '4': isdo=GetTop_LinkedStack(top,&x);
if(isdo==0)
{
printf("查找失败");
}
else
{
printf("查找成功");
printf("栈顶元素为 %4d",x);
}
printf("\n\n\n\t\t\t");
break;
case '5': printf("输出数据");
shuchu(top);
printf("\n\n\n\t\t\t");
break;
}
fflush(stdin);
system("pause");
menu();
}
return 0;
}
void menu()
{ system("cls");
printf("\t\t1-创建\n");
printf("\t\t2-输入\n");;
printf("\t\t3-删除栈顶元素\n");
printf("\t\t4-查找栈顶元素\n");
printf("\t\t5-输出\n");
printf("\t\t#-quit\n");
printf("Please select: ");
}
LinkedStack Init_LinkedStack()
{
LinkedStack top=(LinkedStackNode *)malloc(sizeof(LinkedStackNode));
if(top!=NULL)
{ top->next=NULL;
}
return top;
}
int Push_LinkedStack(LinkedStack top,elemtype x)
{
LinkedStackNode *node;
node=(LinkedStackNode *)malloc(sizeof(LinkedStackNode));
if(node==NULL)
{
return 0;
}
node->data=x;
node->next=top->next;
top->next=node;
return 1;
}
int Pop_LinkedStack(LinkedStack top,elemtype * x)
{
LinkedStackNode *node;
if(top->next==NULL)
{
return 0;
}
else
{
node=top->next;
*x=node->data;
top->next=node->next;
free(node);
return 1;
}
}
int GetTop_LinkedStack(LinkedStack top,elemtype * x)
{
if(top->next==NULL)
{
return 0;
}
else
{
*x=top->next->data;
return 1;
}
}
void shuchu(LinkedStack top)
{
LinkedStackNode *p;
printf("链栈中的元素:");
for(p=top->next;p!=NULL;p=p->next)
{
printf("%4d",p->data);
}
}