栈的链式存储的优点——不会溢出,永远有空间
用链表存储的话,最好有头节点
下面是基本操作
1.结构体定义
#include <stdio.h>
#include <stdlib.h>
struct snode
{
char data;
struct snode* next;
};
typedef snode * stack;
//创建堆栈
//这里我们要创建一个头节点
stack createStack()
{
stack s;
s=(stack)malloc(sizeof(struct snode));
s->next=NULL;
return s;
}
2.创建堆栈
//创建堆栈
//这里我们要创建一个头节点
stack createStack()
{
stack s;
s=(stack)malloc(sizeof(struct snode));
s->next=NULL;
return s;
}
3.判断是否为空
bool isEmpty(stack s)
{
return s->next==NULL;
}
4.入栈
bool push(stack s,char x)
{
stack tmp=(stack)malloc(sizeof(struct snode));
tmp->data=x;
tmp->next=s->next;
s->next=tmp;
return true;
}
4.出栈
char pop(stack s)
{
if(isEmpty(s))
return '0';
else{
stack tmp=s->next;
char tmp_data=tmp->data;
s->next=tmp->next;
free(tmp);
return tmp_data;
}
}