3.1 Describe How do you could use a single array to implement three stacks.
This problem lets us use an array to implement three stacks, the book gives two methods, the first method is fixed-length split fixed division, that is, the length of each stack is the same, with a common one array buffer to save three stacks of content, the first one-third is a stack, the middle One-third is the second stack , after One-third is the third stack, and then also to record the current number of elements of each stack, and then implement the basic operation of the stack push, pop, top and empty, see the code as follows:
classThreestacks { Public: Threestacks (intsize): _stacksize (size) {_buffer.resize ( size*3,0); _stackcur.resize (3, -1); } voidPushintStackidx,intval) { if(_stackcur[stackidx] +1>=_stacksize) {cout<<"Stack"<< Stackidx <<"is full!"<<Endl; } ++_stackcur[stackidx]; _buffer[stackidx* _stacksize + _stackcur[stackidx]] =Val; } voidPopintstackidx) { if(Empty (Stackidx)) {cout<<"Stack"<< Stackidx <<"is empty!"<<Endl; } _buffer[stackidx* _stacksize + _stackcur[stackidx]] =0; --_stackcur[stackidx]; } intTopintstackidx) { if(Empty (Stackidx)) {cout<<"Stack"<< Stackidx <<"is empty!"<<Endl; } return_BUFFER[STACKIDX * _stacksize +_stackcur[stackidx]]; } BOOLEmptyintstackidx) { return_STACKCUR[STACKIDX] = =-1; } Private: int_stacksize; Vector<int>_buffer; Vector<int>_stackcur;};
The second method is flexible segmentation flexible divisions, this method is more complex, here is not fine.
[Careercup] 3.1 Implement three Stacks using array using arrays to implement three stacks