考研 《顺序栈的实现》有源代码 栈顶指针为-1和0的两种情况
栈顶指针为-1的实现方式
#include<stdio.h>
#include<iostream>
// 这一个代码主要写了顺序栈的实现方式
// 出栈,入栈,顺序栈的定义,判断栈为空
// 本个代码基于s.top设置为-1的情况,还有基于0的情况,代码有些许不一样
#define MaxSize 10 // 定义栈中元素的最大个数
typedef int ElemType;
typedef struct {
ElemType data[MaxSize];
int top;
}SqStack;
// 初始化栈
void initStack(SqStack &s){
s.top = -1;
}
// 进栈操作
bool push(SqStack &s, ElemType x){
if (s.top == MaxSize - 1) return false;
s.data[++s.top] = x;
return true;
}
// 出栈操作
bool pop(SqStack &s, ElemType &x){
if (s.top == -1) return false;
x = s.data[s.top--];
return true;
}
// 判断栈是否为空
bool stackEmpty(SqStack s){
if (s.top == -1) return true;
else return false;
}
// 读取栈顶元素
bool GetTop(SqStack s, ElemType &x){
if (s.top == -1) return false; // 证明顺序栈中没有元素
x = s.data[s.top];
return true;
}
int main(){
// 声明一个顺序栈
SqStack s;
// 对顺序栈进行初始化
initStack(s);
// 测试入栈
push(s,888);
push(s,999);
// 为了测试,我们采用不合栈这种逻辑结构的情况进行测试
printf("第一个入栈的元素:%d\n", s.data[s.top - 1]);
printf("第二个入栈的元素:%d\n", s.data[s.top]);
/*
运行结果:
第一个入栈的元素:888
第二个入栈的元素:999
*/
return 0;
}
栈顶指针为0的实现方式
#include<stdio.h>
#include<iostream>
// 这一个代码主要写了顺序栈的实现方式
// 出栈,入栈,顺序栈的定义,判断栈为空
// 本个代码基于s.top设置为0的情况 即top指向栈顶元素的下一个位置
#define MaxSize 10 // 定义栈中元素的最大个数
typedef int ElemType;
typedef struct {
ElemType data[MaxSize];
int top;
}SqStack;
// 初始化栈
void initStack(SqStack &s){
s.top = 0;
}
// 进栈操作
bool push(SqStack &s, ElemType x){
if (s.top == MaxSize) return false;
s.data[s.top++] = x;
return true;
}
// 出栈操作
bool pop(SqStack &s, ElemType &x){
if (s.top == 0) return false;
x = s.data[--s.top];
return true;
}
// 判断栈是否为空
bool stackEmpty(SqStack s){
if (s.top == 0) return true;
else return false;
}
// 读取栈顶元素
bool GetTop(SqStack s, ElemType &x){
if (s.top == 0) return false; // 证明顺序栈中没有元素
x = s.data[s.top];
return true;
}
int main(){
// 声明一个顺序栈
SqStack s;
// 对顺序栈进行初始化
initStack(s);
// 测试入栈
push(s,888);
push(s,999);
// 为了测试,我们采用不合栈这种逻辑结构的情况进行测试
printf("第一个入栈的元素:%d\n", s.data[s.top - 2]);
printf("第二个入栈的元素:%d\n", s.data[s.top - 1]);
/*
运行结果:
第一个入栈的元素:888
第二个入栈的元素:999
*/
return 0;
}
如果有问题,欢迎大家在评论区指正!