数据结构(第五期:栈的基础原理与实战)

目录

一、栈的基本原理

二、栈的实战


一、栈的基本原理

定义:栈是只允许在一端进行插入与删除的线性表,首先栈是一种线性表,但限定这种线性表只能在某一端进行插入和删除操作。

栈顶(Top):线性表允许插入和删除的一端。

栈底(Bottom):固定的,不允许进行插入与删除的另一端。

空栈:不含任何元素的空表

通常在考研中会以栈的先进后出的特点进行考察。

二、栈的实战

1.栈的顺序存储结构

在考研中,通常会以顺序栈的方式考察

#include<stdio.h>
#include<stdlib.h>
#define MaxSize 50//数组
typedef int ElemType;
typedef struct{
	int top;//栈顶
	ElemType data;
}SqStack

2.初始化栈

栈空一般用top=-1表示

void InitStack(SqStack &s){
	s.top=-1;
}

3.判断空栈

bool StackEmpty(SqStack s){
	if(-1==s.top){
		return false;
	}else{
	return true;	
	}
}

4.入栈

bool push(SqStack &s,ElemType x){
	if(s.top==MaxSize-1){//判断栈是否满 
		return false; 
	}
	s.data[s.top++]=s;
}

5.获取栈顶元素

bool GetTop(SqStack s,ElemType &m){
	if(StackEmpty(s)){
		return false;
	}
	m=s.data[s.top];//获取栈顶元素 
	return true; 
}

6.出栈

bool Pop(SqStack s,ElemType &m){
	if(StackEmpty(s)){
		return false;
	}
	m=s.data[s.top--];
	return true;
}

全部代码

#include<stdio.h>
#include<stdlib.h>
#define MaxSize 50
typedef int ElemType;
typedef struct{
	ElemType data[MaxSize];//数组 
	int top;//始终指向栈顶 
}SqStack;
void InitStack(SqStack &s){
	s.top=-1;//栈为空 
}
bool StackEmpty(SqStack s){
	if(-1==s.top){
		return true;
	}else{
		return false;
	}
}
//入栈 
bool push(SqStack &s,ElemType x){
	//判断栈是否满了
	if(s.top==MaxSize-1){
		return false;
	} 
	s.data[++s.top]=x;//等价于s.top=s.top+1
}
bool GetTop(SqStack s,ElemType &m){
	if(StackEmpty(s)){
		return false;
	}
	m=s.data[s.top];//获取栈顶元素 
	return true; 
}
bool Pop(SqStack s,ElemType &m){
	if(StackEmpty(s)){
		return false;
	}
	m=s.data[s.top--];
	return true;
}
int main(){
	SqStack s;
	InitStack(s);
	bool flag; 
	flag=StackEmpty(s);
	if(flag){
		printf("The stack is Empty!\n");
	}
	push(s,3);
	push(s,4);
	push(s,5); 
	push(s,6);
	ElemType m;
	flag =GetTop(s,m);
	if(flag){
		printf("get top %d\n",m);
	}
	flag=Pop(s,m);
	if(flag){
		printf("pop element %d\n",m);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

文艺小青年111

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值