[Careercup] 3.1 Implement three Stacks using array using arrays to implement three stacks

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.