数据结构基础--栈的顺序实现与链式实现C++

栈的定义

栈是一种只能在一端进行插入或者删除操作的线性表

栈的逻辑结构:线性表,可以插入或删除的一段叫做栈顶,另一端叫做栈底。

顺序实现

一个top指针指向栈顶

栈的top值不一定设置为-1,只要能够满足先进后出的特性即可。

元素进栈:

元素出栈:

此时,3,4虽然仍保存在数组中,但已经出栈,不属于栈内

判断栈空或栈满

#include<iostream> 
using namespace std;

#define MAX 100

typedef struct{
	int data[MAX];//栈中存放的元素 
	int top;//栈顶指针 
}SqStack;
//初始化栈,设置栈顶指针位置top为-1 
void InitStack(SqStack &S){
	S.top = -1;
} 
//判断栈是否为空 
bool StackEmpty(SqStack S){
	if(S.top < 0) return true;
	else return false;
}
//入栈 
bool pushStack(SqStack &S,int x){
	if(S.top == MAX - 1) return false;
	S.top++;
	S.data[S.top] = x;
	return true;
}
//出栈 
bool popStack(SqStack &S,int &x){
	if(StackEmpty(S)) return false;
	x = S.data[S.top--];
	return true;
} 
//获取栈顶元素 
bool getElem(SqStack S,int &x){
	if(StackEmpty(S)) return false;
	x = S.data[S.top];
	return true;
}
int main(){
	SqStack S;
	InitStack(S);
	pushStack(S,5);
	pushStack(S,4);
	pushStack(S,3);
	pushStack(S,2);
	pushStack(S,1);
	int x;
	popStack(S,x);
	cout<<"弹出的栈顶元素为"<<x<<endl;
	getElem(S,x);
	cout<<"取到的栈顶元素为:"<<x<<endl; 
	while(S.top >= 0){
		popStack(S,x);
		cout<<"弹出的栈顶元素为"<<x<<endl;
	}
	
	return 0;
}

 

链式存储

 

#include<iostream>
#include<malloc.h>
using namespace std;

typedef struct LNode{
	int data;//数据域
	struct LNode* next;
}*LinkStack; 
void InitStack(LNode *&S){
	S = (LNode*)malloc(sizeof(LNode));//制造一个头结点 
	S->next = NULL;
}
bool StackEmpty(LNode *S){
	if(S->next == NULL) return true;
	else return false;
} 
//链式存储中只要有足够的内存就不会栈满,所以入栈无需判断栈是否已满 
void pushStack(LNode *&S,int x){
	LNode *p;
	p = (LNode*)malloc(sizeof(LNode));
	p->next = NULL;
	p->data = x;
	p->next = S->next;
	S->next = p;
}
//出栈 
bool popStack(LNode *&S,int &x){
	LNode *p;
	if(StackEmpty(S)) return false;
	p = S->next;
	x = p->data;
	S->next = p->next;
	free(p);
	return true;
}
//取栈顶元素 
bool getElem(LNode *S,int &x){
	if(StackEmpty(S)) return false;
	x = S->next->data;
	return true;
}
int main(){
	LinkStack S;
	InitStack(S);
	pushStack(S,5);
	pushStack(S,4);
	pushStack(S,3);
	pushStack(S,2);
	pushStack(S,1);
	int x;
	popStack(S,x);
	cout<<"弹出的栈顶元素为"<<x<<endl;
	getElem(S,x);
	cout<<"取到的栈顶元素为:"<<x<<endl; 
	while(S->next){
		popStack(S,x);
		cout<<"弹出的栈顶元素为"<<x<<endl;
	}
	
	return 0;
}

 

图片来源于率辉老师的数据结构课程

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值