0.概述
本文首先以思维导图的方式介绍了栈的基本知识,其次介绍栈的本质,最后给出栈的存储结构实现代码:顺序栈和链栈1. 栈的
本质
:操作受限的线性表2. 栈的
特点
:先进后出3.
注意点
:栈只是限制了插入和删除的操作位置
,并没有限制栈插入删除的操作时间
,即:进栈和出栈可以交叉次序进行,此处常会设置选择题4.
顺序栈和链栈比较:
顺序栈和链栈基本操作时间复杂度均为O(1)
,唯一可比的只有空间性能
。一般情况下,当栈使用过程中元素个数变化较大时,采用链栈
,反之,采用顺序栈
。
1.基本知识
2.实现代码:
1.顺序栈代码实现
#include<bits/stdc++.h>
using namespace std;
#define MaxSize 10 // 栈所能存储最大值
typedef struct{
int data[MaxSize];
int top; // 指针
}SeqStack;
//0.初始化操作
void InitStack(SeqStack &S){
S.top=-1;
}
//1.判断栈空
bool Empty(SeqStack &S){
if(S.top=-1){
return true;
}
return false;
}
//2.进栈
bool Push(SeqStack &S,int x){
if(S.top==MaxSize-1){
return false;
}else{
S.data[++S.top]=x;
return true;
}
}
//3.出栈
bool Pop(SeqStack &S,int &x) { // x将出栈的值带回
if(S.top==-1){
return false;
} else{
x=S.data[S.top--];
return true;
}
}
//4.获取栈顶元素
bool GetTop(SeqStack &S,int &x) { // x将栈顶的值带回
if(S.top==-1){
return false;
} else{
x=S.data[S.top];
return true;
}
}
//主程序
int main(){
SeqStack S;
InitStack(S); // 初始化
//1.进栈3,5
if(Push(S,3)&&Push(S,5)){
cout<<"进栈成功"<<endl;
} else{
cout<<"进栈失败"<<endl;
}
//2.出栈
int x;
if(Pop(S,x)){
cout<<"出栈元素:"<<x<<endl;
}else{
cout<<"出栈失败"<<endl;
}
//3.取栈顶元素
if(GetTop(S,x)){
cout<<"栈顶元素:"<<x<<endl;
} else{
cout<<"取栈顶元素失败!"<<endl;
}
return 0;
}
1.链栈代码实现
#include<bits/stdc++.h>
using namespace std;
typedef struct LNode{ //栈存储的结点
int data;
struct LNode *next;
}LNode,*LinkStack;
//0.初始化栈——使用不带头节点的单链表
void InitStack(LinkStack &S){
S=NULL;
}
//1.判断栈空
bool Empty(LinkStack S){
if(S==NULL){
return true;
}
return false;
}
//2.进栈
bool Push(LinkStack &S,int x){
LNode *s=(LNode *)malloc(sizeof(LNode));
s->data=x;
s->next=NULL;
if(S==NULL){ //判断进栈是否为第一个元素
S=s;
}
else{
s->next=S->next;
S->next=s;
}
return true;
}
//3.出栈操作
bool Pop(LinkStack &S,int &x){
if(S==NULL){
return false;
}
else{
LNode *p=S; //指向第一个元素,方便删除后释放空间
x=p->data;
S=p->next;
free(p);
return true;
}
}
//4.取栈顶元素
bool GetTop(LinkStack &S,int &x){
if(S==NULL){
return false;
}
else{
LNode *p=S; //指向第一个元素,便于理解
x=p->data;
return true;
}
}
//主程序
int main(){
LinkStack S;
InitStack(S); // 初始化
//1.进栈3,5
if(Push(S,3)&&Push(S,5)){
cout<<"进栈成功"<<endl;
} else{
cout<<"进栈失败"<<endl;
}
//2.出栈
int x;
if(Pop(S,x)){
cout<<"出栈元素:"<<x<<endl;
}else{
cout<<"出栈失败"<<endl;
}
//3.取栈顶元素
if(GetTop(S,x)){
cout<<"栈顶元素:"<<x<<endl;
} else{
cout<<"取栈顶元素失败!"<<endl;
}
return 0;
}