头文件:
#include <stdio.h>
#include <malloc.h>
typedef char ElemType;
typedef struct linknode
{
ElemType data;
struct linknode *next;
}LiStack;
void InitStack(LiStack *&s); //初始化栈
void DestroyStack(LiStack *&s); //销毁栈
int StackLength(LiStack *s); //返回栈长度
bool StackEmpty(LiStack *s); //判断栈是否为空
void Push(LiStack *&s,ElemType e); //入栈
bool Pop(LiStack *&s,ElemType &e); //出栈
bool GetTop(LiStack *s,ElemType &e); //取栈顶元素
void DispStack(LiStack *s); //输出栈中元素
函数实现:
#include "2.h"
void InitStack(LiStack *&s)
{
s=(LiStack*)malloc(sizeof(LiStack));
s->next=NULL;
}
void DestroyStack(LiStack *&s)
{
LiStack *p=s->next;
while(p!=NULL)
{
free(s);
s=p;
p=s->next;
}
free(s);
}
int StackLength(LiStack *s)
{
int i=0;
LiStack *p=s->next;
while(p!=NULL)
{
i++;
p=p->next;
}
return (i);
}
bool StackEmpty(LiStack *s)
{
return(s->next==NULL);
}
void Push(LiStack *&s,ElemType e)
{
LiStack*p;
p=(LiStack*)malloc(sizeof(LiStack));
p->next=s->next;
s->next=p;
p->data=e;
}
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;
}
void DispStack(LiStack *s)
{
LiStack *p;
p=s->next;
if(p!=NULL)
{
printf("%c",p->data);
p=p->next;
}
printf("\n");
}
主函数:
#include "2.h"
int main()
{
ElemType e;
LiStack *s;
printf("(1)初始化链栈s\n");
InitStack(s);
printf("(2)链栈为%s\n",(StackEmpty(s)?"空":"非空"));
printf("(3)依次进链栈元素a,b,c,d,e\n");
Push(s,'a');
Push(s,'b');
Push(s,'c');
Push(s,'d');
Push(s,'e');
printf("(4)链栈为%s\n",(StackEmpty(s)?"空":"非空"));
printf("(5)链栈长度:%d\n",StackLength(s));
printf("(6)从链栈顶到链栈底元素:");DispStack(s);
printf("(7)出链栈序列:");
while (!StackEmpty(s))
{ Pop(s,e);
printf("%c ",e);
}
printf("\n");
printf("(8)链栈为%s\n",(StackEmpty(s)?"空":"非空"));
printf("(9)释放链栈\n");
DestroyStack(s);
return 0;
}
结果: