前言
栈(Stack)是一种只允许在一端进行插入或删除操作的线性表。
采用链式存储的栈称为链栈。
栈顶(Top)是允许进行插入删除的一端。
栈底(Bottom)是固定不允许插入删除的一端。
栈的操作特性概括为后进先出(Last In First Out,LIFO)。
相关知识:
C++结构体
C++指针
C++引用
线性表之单链表
类型描述
假定线性表的元素类型为ElemType。
栈的顺序存储类型可描述为:
#define ElemType int
typedef struct LNode{
ElemType data;
struct LNode *next;
}*LiStack;
基本操作的实现
1.基本操作的实现取决于采用哪种存储结构,存储结构不同,算法的实现也不同;
2.链栈的优点是便于多个栈共享存储空间和提高其效率,且不存在栈满上溢的情况;
3.这里规定的是带头结点的链栈,对于不带头结点的链栈操作会有所不同;
4.进栈操作:无需判断栈满,使用头插法插入头结点的下一个位置;;
5.出栈操作:栈非空时,先取出头结点的下一个结点的值,再更改指针,记得释放空间;
6.栈空条件:S->next != NULL 。
//
// Created by Evian on 2020/3/8.
// 链栈
#include <iostream>
using namespace std;
#define ElemType int
typedef struct LNode{
ElemType data;
struct LNode *next;
}*LiStack;
void InitStack(LiStack &S);
bool isEmpty(LiStack S);
bool Push(LiStack &S, ElemType e);
ElemType Pop(LiStack &S);
void Display(LiStack S);
int main(){
LiStack stack = new LNode();
InitStack(stack);
Push(stack, 1);
Push(stack, 2);
Push(stack, 3);
Push(stack, 4);
Display(stack);
Pop(stack);
Display(stack);
return 0;
}
//初始化,头结点
void InitStack(LiStack &S){
S->next = nullptr;
}
bool isEmpty(LiStack S){
return S->next == nullptr;
}
bool Push(LiStack &S, ElemType e){
LNode *p = new LNode();
p->data = e;
p->next = S->next;
S->next = p;
return true;
}
ElemType Pop(LiStack &S){
if (isEmpty(S)){
cout<<"栈为空"<<endl;
return -1;
} else{
LNode *p = S->next;
ElemType x = p->data;
S->next = p->next;
free(p);
cout<<"Pop: "<<x<<endl;
return x;
}
}
//打印栈,栈顶在前
void Display(LiStack S){
if (isEmpty(S)){
cout<<"栈为空"<<endl;
} else{
LNode *p = S->next;
while(p->next != nullptr){
cout<<p->data<<"--->";
p = p->next;
}
cout<<p->data<<endl;
}
}
以下为打印结果:
4--->3--->2--->1
Pop: 4
3--->2--->1
如有错误,还请指正!TkY 0.0