DoubleStack.h
#pragma once #include<iostream> using namespace std; class DoubleStack { public: int* V; int top[2]; int maxSize; //由于题目没要求,就不写栈满处理函数了,数组的初始化大小稍微大一点 DoubleStack(int size = 100) { maxSize = size; V = new int[maxSize]; top[0] = -1; top[1] = maxSize; } bool isEmpty(int index) { //题目要求写的方法,所以适当地保证方法的健壮性 if (index == 0) { return top[0] == -1; } else if (index == 1) { return top[1] == maxSize; } else { cerr << "INDEX_EXCEPTION!!!" << endl; exit(1); } } bool isFull() { return top[0] + 1 == top[1]; } void push(int index, int e) { if (isFull() == true) { //本来插入栈满不该写cerr的,应该用栈满函数处理 //但题目没要求写栈满函数,就直接cerr来处理吧 cerr << "OVERFLOW_EXCEPTION" << endl; exit(1); } if (index == 0) { V[++top[0]] = e; } else { V[--top[1]] = e; } } bool pop(int index, int& e) { bool res = true; if (isEmpty(index) == true) { res = false; } else { if (index == 0) { e = V[top[0]--]; } else { e = V[top[1]++]; } } return res; } };
main.cpp
#include"DoubleStack.h" int main() { DoubleStack s; int arr[] = { 1,2,3,4,5,6,7,8,9,10 }; for (int i = 0; i < 10; i++) { s.push(i % 2, arr[i]); //i%2应该知道是做什么用的吧。用这个可以简化代码 } int temp; for (int i = 0; i < 2; i++) { while (s.pop(i,temp)) { cout << temp << " "; } cout << endl; } return 0; }
课后习题 3.11 共享栈 类定义、判断栈空、判断栈满、进栈、出栈
原文:https://www.cnblogs.com/SlowIsFast/p/12631252.html