#include<stdio.h>
#include<stdlib.h>
typedef char ElemType;
typedef struct linknode
{
ElemType data;
struct linknode * next;
int length;
}LiStack;
void InitStack(LiStack *&s);
void DestroyStack(LiStack *&s);
bool StackEmpty(LiStack *s);
void Push(LiStack *&s,ElemType e);
bool Pop(LiStack *&s,ElemType &e);
bool GetTop(LiStack *s,ElemType &e);
int StackLength(LiStack *s);
void InitStack(LiStack *&s)
{
s=(LiStack*)malloc(sizeof(LiStack));
s->next=NULL;
s->length;
}
void DestroyStack(LiStack *&s)
{
LiStack *p,*q=s->next;
while(q!=NULL)
{
free(p);
p=q;
q=p->next;
}
free(p);
}
bool 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;
}
bool Pop(LiStack *&s,ElemType &e)
{
LiStack *p;
if(s->next==NULL)
return false;
p=s->next;
e=p->data;
s->next=p->next;
free(p);
return true;
}
bool GetTop(LiStack *s,ElemType &e)
{
if(s->next==NULL)
return false;
e=s->next->data;
return true;
}
int StackLength(LiStack *s)
{
int n=0;
LiStack*p=s;
while(p->next!=NULL)
{
n++;
p=p->next;
}
return(n);
}
void main()
{
LiStack *s,*p;
char a[]={'a','b','c','d','e'};
char e;
int i;
InitStack(s);
if(StackEmpty(s))
printf("链表s为空!\n");
else
printf("链表s不为空!\n");
for(i=0;i<5;i++)
{
e=a[i];
Push(s,e);
}
if(StackEmpty(s))
printf("链表s为空!\n");
else
printf("链表s不为空!\n");
printf("链栈的长度:%d\n",StackLength(s));
p=s;
printf("输出从栈顶到栈底元素:");
for(i=0;i<5;i++)
{
GetTop(s,e);
printf("%c",e);
s=s->next;
}
printf("\n");
s=p;
printf("输出出链栈的序列:");
for(i=0;i<5;i++)
{
Pop(s,e);
printf("%c",e);
}
printf("\n");
if(StackEmpty(s))
printf("链表s为空!\n");
else
printf("链表s不为空!\n");
DestroyStack(s);
}