#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define MaxSize 50
typedef char ElemType;
typedef struct linknode
{
ElemType data;
struct linknode *next;
}LiStack;
void InitStack(LiStack *&s)
{
s=(LiStack *)malloc(sizeof(LiStack));
s->next=NULL;
}
void DestoryStack(LiStack( *&s))
{
LiStack *p=s,*q=s->next;
while(q!=NULL)
{
free(p);
p=q;
q=p->next;
}
free(q);
}
int StackEmpty(LiStack *s)
{
return(s->next==NULL);
}
void Push(LiStack(*& s),ElemType e)
{
LiStack *p;
p=(LiStack *)malloc(sizeof(LiStack));
p->data=e;
p->next=s->next;
s->next=p;
}
int Pop(LiStack * &s,ElemType &e)
{
LiStack *p;
if(s->next==NULL)
return 0;
p=s->next;
e=p->data;
s->next=p->next;
free(p);
return 1;
}
int GetTop(LiStack *s,ElemType &e)
{
if (s->next==NULL) //栈为空的情况,即栈下溢出
return 0;
e=s->next->data;
return 1;
}
int StackLength(LiStack *s)
{
int i=0;
LiStack *p;
p=s->next;
while(p!=NULL)
{
i++;
p=p->next;
}
return i;
}
void DispStack(LiStack *s)
{
LiStack *p=s->next;
while(p!=NULL)
{
printf("%c",p->data);
p=p->next;
}
printf("\n");
}
int main()
{
LiStack *s;
ElemType e;
printf("初始化栈s\n");
InitStack(s);
printf("栈为:%s\n",(StackEmpty(s)?"空":"非空"));
printf("依次进栈元素a,b,c,d,e\n");
Push(s,'a');
Push(s,'b');
Push(s,'c');
Push(s,'d');
Push(s,'e');
printf("栈为:%s\n",(StackEmpty(s)?"空":"非空"));
printf("显示栈:");
DispStack(s);
printf("栈长:%d\n",StackLength(s));
GetTop(s,e);
printf("栈顶元素:%c\n",e);
printf("出栈:");
while(!StackEmpty(s))
{
Pop(s,e);
printf("%c",e);
}
printf("\n");
printf("栈为:%s\n",(StackEmpty(s)?"空":"非空"));
printf("销毁栈\n");
DestoryStack(s);
return 0;
}