ShareStack.h
#pragma once #include<iostream> using namespace std; class ShareStack { public: int* v; int maxSize; int top[2]; int bottom[2]; ShareStack(int size = 5) { maxSize = size; v = new int[maxSize]; top[0] = bottom[0] = -1; top[1] = bottom[1] = maxSize; } bool IsFull() { return top[0] + 1 == top[1]; } void overflowProcess() { int* s = new int[maxSize * 2]; for (int i = 0; i <= top[0]; i++) { s[i] = v[i]; } for (int i = maxSize - 1; i >= top[1]; i--) { s[i + maxSize] = v[i]; } top[1] += maxSize; bottom[1] = 2 * maxSize; maxSize *= 2; delete[]v; v = s; } void push(int elem, int which) { //which表示操作哪个栈 if (IsFull() == true) { overflowProcess(); } if (which == 0) { top[0]++; } else { top[1]--; } v[top[which]] = elem; } bool pop(int& elem, int which) { bool res; if (top[which]==bottom[which]) { res = false; } else { elem = v[top[which]]; if (which == 0) { top[0]--; } else { top[1]++; } res = true; } return res; } };
main.cpp
#include"ShareStack.h" int main() { ShareStack s; int a[] = { 1,3,5,7,9 }; int b[] = { 2,4,6,8,10 }; //测试栈溢出处理机制。构造函数默认数组大小为5 for (int i = 0; i < 5; i++) { s.push(a[i], 0); s.push(b[i], 1); } cout << "V:" << endl; //原则上不能有下面这种操作,但是为了方便看数组里的元素,不想调试了 for (int i = 0; i < s.maxSize; i++) { cout << s.v[i] << " "; } cout << endl; cout << "top[0]:" << s.top[0] << " top[1]:" << s.top[1] << endl; bool bl; int e; for (int i = 0; i < 2; i++) { while (s.top[i] != s.bottom[i]) { bl = s.pop(e, i); cout << e << " "; } cout << endl; } return 0; }