
数据结构之堆栈
堆栈的链式存储
1.定义一个结构体
typedef struct snode *stack;
struct snode{
elementtype data;
struct snode *next;
};
2.堆栈初始化
stack createstack(){
stack s;
s=(stack)malloc(sizeof(struct snode));
s->next = null;
return s;
}
3.判断堆栈s是否为空
int isempty(stack s){
return (s->next==null);
}
4.插入一个数据
void push(stack s,elementtype item){
struct snode *tmpcell;
tmpcell=(stack)malloc(sizeof(struct snode));
tmpcell->data = item;
tmpcell->next = s->next;
s->next=tmpcell;
}
5.删除一个数据
elementtype pop(stack s){
struct snode *a;
elementtype item;//保存删除的数据
if(isempty(s)){
printf("栈为空");
}else{
a=s->next;
s->next = a->next;
item = a->data;
free(a);
return item;
}




近期评论