一、前言
接上一篇的顺序栈,这篇文章用来写采用链接方式表示栈----链栈。
二、存储结构
typedef char DataType;
struct node//单链表结点定义
{
DataType info;
struct node* link;
};
typedef struct node* PNode;
struct LinkStack//链接栈类型定义
{
PNode top;//指向栈顶结点
};
typedef struct LinkStack* PLinkStack;
三、c语言实现链栈
初始化一个空的链栈
PLinkStack createNullStack_link()
{
PLinkStack s = (PLinkStack)malloc(sizeof(struct LinkStack));
s->top = NULL;
return s;
}
栈空判断
判断栈是否为空,若为空,返回值为1,否则返回值为0,若栈不存在,则返回-1
int isNullStack_link(PLinkStack L)
{
return (L->top==NULL);
}
压栈
在栈中插入数据元素x,若插入不成功,返回0;插入成功返回值为1
int push_link(PLinkStack L,DataType x)
{
PNode s = (PNode)malloc(sizeof(struct node));
if(s == NULL)return 0;
s->info = x;
s->link = L->top;
L->top = s;
return 1;
}
弹栈
弹栈并返回删除元素,若栈为空,则返回-1
DataType pop_link(PLinkStack L)
{
if(L->top == NULL)return -1;
int t = L->top->info;
PNode p = L->top;
L->top = L->top->link;
free(p);
return p;
}
取栈顶元素
取栈顶元素返回,若栈为空,则返回-1
DataType top_link(PLinkStack L)
{
if (L->top == NULL) return -1;
int t = L->top->info;
return t;
}
销毁栈,释放栈所占存储空间
返回值为销毁的栈中现有数据元素的个数,若待销毁的线性表不存在,则返回0
int destroystack_link(PLinkStack L)
{
int cnt = 0;
if(L == NULL)return 0;
struct node *p = L->top;
struct node *q;
free(L);
while(p->link != NULL)
{
q = p->link;
cnt++;
free(p);
p = q;
}
return cnt++;
}