目录
一、栈的基本原理
定义:栈是只允许在一端进行插入与删除的线性表,首先栈是一种线性表,但限定这种线性表只能在某一端进行插入和删除操作。
栈顶(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);
}
}