//链式栈的基本操作 计科1003 ZhangYusi 2011.10.07
#include<stdlib.h>
#include<stdio.h>
#include<conio.h>
//链式栈的定义
typedef char stackdata;
typedef struct node
{
stackdata data;//结点数据
struct node *link;//结点链指针
}stacknode;
typedef stacknode *linkstack;
linkstack top;//栈顶指针
//1.建立链式栈
linkstack createstackF()
{
char ch;
stacknode *s;
linkstack head=(linkstack)malloc(sizeof(stacknode));
head->link=NULL;
while((ch=getchar())!='\n')
{
s=(stacknode *)malloc(sizeof(stacknode));//建立新结点
s->data=ch;
s->link=head->link;
head->link=s;
}
return head;
}
//2.判断栈是否为空:空则返回1,否则返回0
int stackempty(linkstack top)
{
return top->link == NULL;
}
//3.进栈
int push(linkstack top,stackdata x)
{
stacknode *p=(stacknode *)malloc(sizeof(stacknode));
p->data=x;
p->link=top->link;
top->link=p;
return 1;
}
//4.出栈
int pop(linkstack top,stackdata &x)
{
if(stackempty(top))
{
return 0;
}
stacknode *p=top->link;
top->link=p->link;
x=p->data;
free(p);
return 1;
}
//5.取栈顶元素
int gettop(linkstack top,stackdata &x)
{
if(stackempty(top))
{
return 0;
}
x=top->link->data;
return 1;
}
//6.置空栈
void emptystack(linkstack top)
{
top->link=NULL;
}
//菜单
int menu()
{
system("cls");
printf("请建立初始化链式栈:\n");
top=createstackF();
while(1)
{
system("cls");
printf("*************************************************\n");
printf("*************************************************\n");
printf("******* 1.判断栈是否空 *******\n");
printf("******* 2.进栈 *******\n");
printf("******* 3.出栈 *******\n");
printf("******* 4.取栈顶元素 *******\n");
printf("******* 5.置栈空 *******\n");
printf("******* 0.退出 *******\n");
printf("*************************************************\n");
printf("*************************************************\n");
int n;
scanf("%d",&n);
switch(n)
{
case(1):system("cls");
stackempty(top);
if(stackempty(top) == 1)
{
printf("链式栈为空!\n");
}
else
{
printf("链式栈非空!\n");
}
getch();
break;
case(2):system("cls");
stackdata x;
printf("请输入数据:\n");
x=getch();
push(top,x);
if(push(top,x) == 1)
{
printf("新元素%c已进栈!",x);
}
getch();
break;
case(3):system("cls");
stackdata y;
pop(top,y);
if(pop(top,y) == 0)
{
printf("栈为空!\n");
}
else
{
printf("栈顶元素%c已出栈!",y);
}
getch();
break;
case(4):system("cls");
stackdata z;
gettop(top,z);
if(gettop(top,z) == 0)
{
printf("栈为空!\n");
}
else
{
printf("栈顶元素为%c",z);
}
getch();
break;
case(5):system("cls");
emptystack(top);
getch();
break;
case(0):
return 0;
break;
default:
printf("输入有误!");
getch();
break;
}
}
}
int main()
{
menu();
getch();
return 0;
}