栈——存储结构实现(顺序栈、链栈)

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;
} 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值