博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
两个顺序栈共享空间基本实现(C++)
阅读量:4049 次
发布时间:2019-05-25

本文共 2053 字,大约阅读时间需要 6 分钟。

这一个示例就是在顺序栈的基础上加上了一些条件判断,使得两个相同数据类型的栈能够共用一个空间。节省内存的消耗。试验代码和函数功能如下:

template
class sqStack {
private: T data[MAXSIZE]; int top1; int top2;public: sqStack(); //默认构造函数; T GetTop(int c) const; //得到栈c的栈顶元素; bool Push(const T &e, int c); //将e压入第c号栈; bool Pop(int c); //将第c号栈的栈顶元素弹出; bool isEmpty(int c) const; //判断第c个栈是否为空; bool isFull() const; //判断内存空间有没有占满; void ClearStack(int c); //清楚第c个栈;};

共享空间的头文件

#pragma once#ifndef STACK_H_#define STACK_H_#define MAXSIZE 1000template
class sqStack {
private: T data[MAXSIZE]; int top1; int top2;public: sqStack(); T GetTop(int c) const; bool Push(const T &e, int c); bool Pop(int c); bool isEmpty(int c) const; bool isFull() const; void ClearStack(int c);};template
sqStack
::sqStack() {
top1 = -1; top2 = MAXSIZE;}template
T sqStack
::GetTop(int c) const{
if (isEmpty(c)) {
cout << "The stack is empty!\n"; exit(EXIT_FAILURE); } else {
if (c == 1) return data[top1]; else if (c == 2) return data[top2]; }}template
bool sqStack
::Push(const T &e, int c){ if (isFull()) return false; else { if (c == 1) { top1 += 1; data[top1] = e; } else if (c == 2) { top2 -= 1; data[top2] = e; } }}template
bool sqStack
::Pop(int c){ if (isEmpty(c)) return false; else { if (c == 1) top1 -= 1; else if (c == 2) top2 += 1; } return true;}template
bool sqStack
::isEmpty(int c) const{ if(c==1) return (top1 == -1); if (c == 2) return (top2 == MAXSIZE);}template
bool sqStack
::isFull() const{ return (top1 + 1 == top2);}template
void sqStack
::ClearStack(int c){ if (c == 1) top1 = -1; else if (c == 2) top2 = MAXSIZE;}#endif

共享空间的示例用法

#include
#include
#include"stack.h"using namespace std;void main(){
sqStack
book; book.Push("BOOK THIEF",1); book.Push("KITE RUNNER",2); book.Push("THE OLD MAN",1); cout << book.GetTop(1) << endl; cout << book.GetTop(2) << endl; book.Pop(1); cout << book.GetTop(1) << endl; book.ClearStack(1); cout << book.GetTop(1) << endl;}

转载地址:http://hsyci.baihongyu.com/

你可能感兴趣的文章
Win10+VS+ESP32环境搭建
查看>>
Ubuntu+win10远程桌面
查看>>
flutter-实现圆角带边框的view(android无效)
查看>>
android 代码实现圆角
查看>>
flutter-解析json
查看>>
android中shader的使用
查看>>
java LinkedList与ArrayList迭代器遍历和for遍历对比
查看>>
drat中构造方法
查看>>
JavaScript的一些基础-数据类型
查看>>
JavaScript基础知识(2)
查看>>
转载一个webview开车指南以及实际项目中的使用
查看>>
android中对于非属性动画的整理
查看>>
一个简单的TabLayout的使用
查看>>
ReactNative使用Redux例子
查看>>
Promise的基本使用
查看>>
coursesa课程 Python 3 programming 统计文件有多少单词
查看>>
coursesa课程 Python 3 programming 输出每一行句子的第三个单词
查看>>
Returning a value from a function
查看>>
coursesa课程 Python 3 programming Functions can call other functions 函数调用另一个函数
查看>>
coursesa课程 Python 3 programming The while Statement
查看>>