3.1 Describe how you could use a single array to implement three stacks.
這道題讓我們用一個陣列來實現三個棧,書上給了兩種方法,第一種方法是定長分割 Fixed Division,就是每個棧的長度相同,用一個公用的一位陣列buffer來儲存三個棧的內容,前三分之一為第一個棧,中間三分之一為第二個棧,後三分之一為第三個棧,然後還要分別記錄各個棧當前元素的個數,然後再分別實現棧的基本操作push, pop, top 和 empty,參見程式碼如下:
class ThreeStacks { public: ThreeStacks(int size) : _stackSize(size) { _buffer.resize(size * 3, 0); _stackCur.resize(3, -1); } void push(int stackIdx, int val) { if (_stackCur[stackIdx] + 1 >= _stackSize) { cout << "Stack " << stackIdx << " is full!" << endl; } ++_stackCur[stackIdx]; _buffer[stackIdx * _stackSize + _stackCur[stackIdx]] = val; } void pop(int stackIdx) { if (empty(stackIdx)) { cout << "Stack " << stackIdx << " is empty!" << endl; } _buffer[stackIdx * _stackSize + _stackCur[stackIdx]] = 0; --_stackCur[stackIdx]; } int top(int stackIdx) { if (empty(stackIdx)) { cout << "Stack " << stackIdx << " is empty!" << endl; } return _buffer[stackIdx * _stackSize + _stackCur[stackIdx]]; } bool empty(int stackIdx) { return _stackCur[stackIdx] == -1; } private: int _stackSize; vector<int> _buffer; vector<int> _stackCur; };
第二種方法是靈活分割 Flexible Divisions,這種方法較為複雜,這裡就不細寫了。