一个数组实现两个栈有很多想法,我先写一种比较简单的,思路如下图所示:
代码如下:
#include<iostream> using namespace std; //一个数组实现两个栈 template <class T> class arraystack { public : arraystack() { _array1 = new T[10]; _array2 = _array1 + 9; _size1 = 0; _size2 = 0; _capacity = 10; } void pusharray1(const T& x) { //判断数组是否已满 if( (_size1+_size2) < _capacity ) { _array1[_size1] = x; _size1++; } else cout<< "该栈已满"<<endl; } void pusharray2(const T& x) { if( (_size1+_size2) < _capacity ) { _array1[_capacity - _size2 - 1] = x; _size2++; } else cout<< "该栈已满"<<endl; } T& GetTop1() { return _array1[_size1 - 1]; } T& GetTop2() { return _array1[_capacity - _size2]; } void poparray1() { //空 // if(_size1 > 0) { _size1--; } else cout<< "该栈为空"<<endl; } void poparray2() { if(_size2 > 0) { _size2--; } else cout<< "该栈为空"<<endl; } private : T* _array1; T* _array2; int _size1; int _size2; int _capacity; }; void Test1() { arraystack< int> a1; a1.pusharray1 (1); a1.pusharray1 (2); a1.pusharray1 (3); a1.pusharray1 (4); a1.pusharray1 (5); cout<<a1.GetTop1 ()<<endl; a1.poparray1 (); cout<<a1.GetTop1 ()<<endl; a1.pusharray2 (10); a1.pusharray2 (9); a1.pusharray2 (8); a1.pusharray2 (7); a1.pusharray2 (6); cout<<a1.GetTop2 ()<<endl; a1.poparray2 (); cout<<a1.GetTop2 ()<<endl; } int main() { Test1(); return 0; }原文链接:https://www.f2er.com/datastructure/382587.html