采用链式存储的栈称为链栈,链栈的优点是便于多个栈共享存储空间和提高其效率,且不存在栈满上溢的情况。通常采用单链表实现(无头结点,Lhead指向栈顶元素)。(参考王道考研书籍)
/*不带头结点的链栈*/
#include<iostream>
#include<cstdio>
//链栈的结构体定义
typedef struct Linknode{
int data;
struct Linknode *next;
}*Listack;
//初始化一个空栈
bool initStack(Listack &s){
s=NULL;
return true;
}
//进栈操作
bool push(Listack &s, int x){
Linknode *p = (Linknode *)malloc(sizeof(Linknode));
p->data = x;
p->next = s;
s = p;
return true;
}
//出栈
bool pop(Listack &s, int &x){
if(s==NULL){
return false;
}else{
x = s->data;
s = s->next;
return true;
}
}
//打印栈的元素,从栈顶开始
void printStack(Listack s){
Linknode *p = s;
while(p!=NULL){
printf("%d",p->data);
if(p->next!=NULL){
printf(" ");
}
p = p->next;
}
printf("\n");
}
int main(){
Listack s;
initStack(s);
push(s, 0),push(s,1),push(s,2),push(s,3);
printf("栈内元素为:(进栈操作后)\n");
printStack(s);
int x = -1;
pop(s, x);
printf("站内元素为:(出栈操作后)\n");
printStack(s);
printf("出栈的元素为%d", x);
return 0;
}