Using two stacks to implement a queue

Source: Internet
Author: User

Using two stacks to implement a queue
    • Number of participants: 3047 time limit: 1 seconds space limit: 32768K
    • By scale: 34.71%
    • Best record: 0 ms|0k(from Tsing elder brother)
Topic description Use two stacks to implement a queue, complete the queue push and pop operations. The elements in the queue are of type int.


Idea 1 (the most common method):
1, when the queue, directly pressed into the STACK1;
2, out of the team, the first Stack1 all the size-1 elements into the Stack2, and then the elements of the stack1 ejected; Finally, the elements in the Stack2 are re-pressed into the S1.

As shown in the following:

1 classSolution2 {3  Public:4     voidPushintnode) {5 Stack1.push (node);6     }7 8     intpop () {9         intT;Ten          while(Stack1.size () >1){ Onet =stack1.top (); A Stack2.push (t); - Stack1.pop (); -         } the         intRT =stack1.top (); - Stack1.pop (); -          while(Stack2.size () >0){ -t =stack2.top (); + Stack1.push (t); - Stack2.pop (); +         } A         returnRT; at     } -  - Private: -stack<int>Stack1; -stack<int>Stack2; -};
View Code

Idea 2 (Optimization):

1, when the queue, directly pressed into the STACK1;
2, when the team, if the Stack2 is not empty, the direct pop-up, if the Stack2 is empty, the Stack1 size-1 elements are pressed into the Stack2, and finally pop up the stack top element in Stack1.

1 classSolution2 {3  Public:4     voidPushintnode) {5 Stack1.push (node);6     }7 8     intpop () {9         intRT;Ten         if(!Stack2.empty ()) { OneRT =stack2.top (); A Stack2.pop (); -         } -         Else{ the              while(Stack1.size () >1){ -RT =stack1.top (); - Stack2.push (RT); - Stack1.pop (); +             } -RT =stack1.top (); + Stack1.pop (); A         } at         returnRT; -     } - Private: -stack<int>Stack1; -stack<int>Stack2; -};
View Code

 

Using two stacks to implement a queue

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.