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