1
数据结构——顺序栈
发布于: 52 分钟前

栈
定义:只能在表的一端(栈顶)进行插入和删除运算的线性表
逻辑结构:一对一关系
存储结构
顺序栈
链栈
运算规则:只能在栈顶运算,且访问结点时依照后进先出(LIFO)或先进后出(FILO)的原则
实现方式
入栈
出栈
读栈顶元素值
建栈
判断栈空
判断栈慢
清空栈
销毁栈
栈的表示和操作的实现
顺序栈的 C++代码实现
#include<iostream>using namespace std;
#define OVERFLOW -2 #define OK 1#define NULL 0#define ERROR -1
#define MAXSIZE 100 // 最大空间
typedef int SElemType;typedef int Status;
typedef struct { SElemType* base; SElemType* top; int stacksize;}SqStack;
// 顺序栈初始化Status InitStack(SqStack& S) { S.base = new SElemType[MAXSIZE]; if (!S.base) return OVERFLOW; S.top = S.base; S.stacksize = MAXSIZE; return OK;}
// 判断顺序栈是否为空bool StackEmpty(SqStack S) { if (S.top == S.base) return true; else return false;}
// 判断是否为满栈bool StackFull(SqStack S) { if (S.top - S.base >= S.stacksize) return true; else return false;}
// 顺序栈的长度int StackLength(SqStack S) { return S.top - S.base;}
// 输出栈顶元素Status Gettop(SqStack S, SElemType& e) { // SElemType* p; if (StackEmpty(S)) // 栈空 return ERROR; // p = S.top - 1; // e = *p; e = *(S.top - 1); return OK;}
// 入栈Status Push(SqStack& S, SElemType e) { if (StackFull(S)) // 满栈 return ERROR; *S.top++ = e; // *S.top = e; // S.top ++; return OK;}
// 出栈Status Pop(SqStack& S, SElemType& e) { if (StackEmpty(S)) // 栈空 return ERROR; e = *--S.top; // S.top --; // e = *S.top; return OK;}
// 清空顺序栈Status ClearStack(SqStack& S) { // S.stacksize = 0; if(S.base) S.top = S.base; cout << "清空成功!" << endl; return OK;}
// 销毁顺序栈Status DestroyStack(SqStack& S) { if (S.base) { delete S.base; S.stacksize = 0; S.base = S.top = NULL; } cout << "销毁成功!" << endl; return OK;}
// 输入void Creat(SqStack& S, int m) { int i; SElemType x; for (i = 1; i < m + 1; i++) { cout << "请输入第" << i << "个元素: "; cin >> x; Push(S, x); // S.stacksize++; }}
// 输出void OutPut(SqStack S) { SElemType* p; p = S.base; while (p < S.top) cout << *p++ << " "; cout << endl;}
int main(){ int m; SElemType e; SqStack S;
/*---------------测试--------------*/ InitStack(S);
cout << "请输入栈的长度: "; cin >> m; Creat(S, m); cout << "栈中元素为: "; OutPut(S);
cout << "顺序栈的长度为: "; cout << StackLength(S) << endl;
// 入栈测试 cout << "请输入入栈元素: "; cin >> e; Push(S, e); cout << "栈中元素为: "; OutPut(S);
cout << "顺序栈的长度为: "; cout << StackLength(S) << endl;
// 获取栈顶元素测试 Gettop(S, e); cout << "栈顶元素为: " << e <<endl;
cout << "顺序栈的长度为: "; cout << StackLength(S) << endl;
// 出栈测试 Pop(S, e); cout << "弹出的元素为: " << e << endl;
cout << "栈中元素为: "; OutPut(S);
cout << "顺序栈的长度为: "; cout << StackLength(S) << endl;
// 清空测试 ClearStack(S); cout << "顺序栈的长度为: "; cout << StackLength(S) << endl;
// 销毁测试 DestroyStack(S); return 0;}
复制代码
请输入栈的长度: 3请输入第1个元素: 1请输入第2个元素: 2请输入第3个元素: 3栈中元素为: 1 2 3顺序栈的长度为: 3请输入入栈元素: 7栈中元素为: 1 2 3 7顺序栈的长度为: 4栈顶元素为: 7顺序栈的长度为: 4弹出的元素为: 7栈中元素为: 1 2 3顺序栈的长度为: 3清空成功!顺序栈的长度为: 0销毁成功!
复制代码
划线
评论
复制
发布于: 52 分钟前阅读数: 2
版权声明: 本文为 InfoQ 作者【若尘】的原创文章。
原文链接:【http://xie.infoq.cn/article/eabf986b19343fdd0d6dbce55】。文章转载请联系作者。
若尘
关注
还未添加个人签名 2021.01.11 加入
还未添加个人简介











评论