0
点赞
收藏
分享

微信扫一扫

数据结构——顺序栈


  • 定义:只能在表的一端(栈顶)进行插入和删除运算的线性表
  • 逻辑结构:一对一关系
  • 存储结构
  • 顺序栈
  • 链栈
  • 运算规则:只能在栈顶运算,且访问结点时依照后进先出(LIFO)或先进后出(FILO)的原则
  • 实现方式
  • 入栈
  • 出栈
  • 读栈顶元素值
  • 建栈
  • 判断栈空
  • 判断栈慢
  • 清空栈
  • 销毁栈

栈的表示和操作的实现

数据结构——顺序栈_C++

数据结构——顺序栈_顺序栈_02


数据结构——顺序栈_C++_03

顺序栈的C++代码实现

#include<iostream>
using namespace std;

#define
#define
#define
#define

#define// 最大空间

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
销毁成功!


举报

相关推荐

0 条评论