顺序栈的实现比较简单,需要注意的是top指针初始化的值,为-1时指向的是栈顶元素,为0时指向的是栈顶元素的下一个元素位置。top指针初始化值的不同也会带来后续Push和Pop操作时的不同(是先移动栈顶指针再赋值,还是相反),这点在写代码时尤其需要注意。这里实现时top指针初始化为-1,也就是指向栈顶元素,并且是以静态数组的形式实现的,无法扩充数组大小,有兴趣的同学也可以尝试使用动态数组实现,其思路与动态顺序表相似,在栈满上溢时分配额外的空间给栈。
下面是顺序栈的实现代码,使用ide为vs2019。
SeqStack.h
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define ElemType int
#define MaxSize 10
//顺序栈定义
typedef struct{
ElemType data[MaxSize];
int top; //栈顶指针
}SeqStack;
void InitStack(SeqStack &s); //初始化栈
void PrintStack(SeqStack s); //打印栈
bool Push(SeqStack& s, ElemType e); //元素进栈
bool Pop(SeqStack& s, ElemType& e); //元素出栈
bool isEmpty(SeqStack s); //判空
bool isfull(SeqStack s); //判满
bool GetTop(SeqStack s, ElemType& e); //查找栈顶元素
SeqStack.c
#include "SeqStack.h"
void InitStack(SeqStack& s) {
s.top = -1; //top指向栈顶元素
}
bool isEmpty(SeqStack s) {
return(s.top == -1);
}
bool isfull(SeqStack s) {
return(s.top == MaxSize);
}
void PrintStack(SeqStack s) {
if (isEmpty(s)) {
printf("栈空!\n");
return;
}
printf("从栈底到栈顶:");
for (int i = 0; i <= s.top; i++) {
printf("%d ", s.data[i]);
}
printf("\n");
}
bool Push(SeqStack& s, ElemType e) {
if (isfull(s)) {
printf("栈满!操作失败\n");
return false;
}
s.data[++s.top] = e; //注意++s.top和s.top++的区别,一个是先移动top指针再赋值,一个是先赋值再移动top指针
return true;
}
bool Pop(SeqStack& s, ElemType& e) {
if (isEmpty(s)) {
printf("栈空!操作失败\n");
return false;
}
printf("%d出栈!\n", s.data[s.top]);
e = s.data[s.top--];
return true;
}
bool GetTop(SeqStack s, ElemType& e) {
if (isEmpty(s)) {
printf("栈空!\n");
return false;
}
e = s.data[s.top];
return true;
}
main.c
#include "SeqStack.h"
//测试
void main() {
SeqStack s;
ElemType e;
InitStack(s);
Push(s, 1);
Push(s, 2);
Push(s, 3);
PrintStack(s);
Pop(s, e);
printf("e:%d\n", e);
PrintStack(s);
GetTop(s, e);
printf("e:%d\n", e);
}
2568



被折叠的 条评论
为什么被折叠?



