前言
日期:2023.7.25
书籍:2024年数据结构考研复习指导(王道考研系列)
内容:实现顺序栈的基本实现,主要功能如下:
❶ 栈的数据结构
❷ 出栈
❸ 入栈
❹ 判栈空
❺ 读栈顶
1.顺序栈的定义
//1.顺序栈的定义
#define MaxSize 50
typedef int Elemtype;
typedef struct Sqstack{
Elemtype data[MaxSize];
int top;//指向栈顶
}Sqstack;
2.顺序栈的初始化和判空
bool Initstack(Sqstack *S){
S->top=-1;
}
bool StackEmpty(Sqstack S){
if(S.top==-1) return true;
else return false;
}
3.顺序栈的出栈和入栈
bool Push(Sqstack *S,Elemtype e){
if(S->top==MaxSize-1) return false;//栈满报错
S->top=S->top+1;
S->data[S->top]=e;
return true;
}
bool Pop(Sqstack *S,Elemtype *e){
if(S->top=-1) return false;
*e=S->data[S->top];
S->top=S->top-1;
return true;
}
4.顺序栈的读取顶元素
bool GetTop(Sqstack S,Elemtype *e){
if(StackEmpty(S)) return false; //栈空报错
*e = S.data[S.top];
return true;
}
完整代码
#include <stdio.h>
#include <stdlib.h>
#define bool char
#define true 1
#define false 0
//1.顺序栈的定义
#define MaxSize 50
typedef int Elemtype;
typedef struct Sqstack{
Elemtype data[MaxSize];
int top;//指向栈顶
}Sqstack;
//2.顺序栈的初始化和判空
bool Initstack(Sqstack *S){
S->top=-1;
}
bool StackEmpty(Sqstack S){
if(S.top==-1) return true;
else return false;
}
//3.顺序栈的出栈和入栈
bool Push(Sqstack *S,Elemtype e){
if(S->top==MaxSize-1) return false;//栈满报错
S->top=S->top+1;
S->data[S->top]=e;
return true;
}
bool Pop(Sqstack *S,Elemtype *e){
if(S->top=-1) return false;
*e=S->data[S->top];
S->top=S->top-1;
return true;
}
//4.顺序栈的读取顶元素
//【9】读栈顶元素
bool GetTop(Sqstack S,Elemtype *e)
{
if(StackEmpty(S)) return false; //栈空报错
*e = S.data[S.top];
return true;
}
int main(){
Sqstack S;
Initstack(&S);
Push(&S,1);
Push(&S,2);
Push(&S,3);
Push(&S,4);
Push(&S,5);
Push(&S,6);
Elemtype X; //用与保存出栈和读栈顶元素返回的变量的值
int count = S.top;
for(int i = 0;i <= count;i++){
printf("i = %d\n",i);
GetTop(S,&X);
printf("GetTop X = %d\n",X);
Pop(&S,&X);
printf("Pop X = %d\n",X);
}
return 0;
}