Problem Description:
Implement a queue with two stacks to complete the push and pop operations of the queue. The elements in the queue are of type int.
Algorithm Analysis:
Push
1. Press the data into the STACK1;
Pop
1. Eject all data from the stack1 to Stack2;
2. Set the first number in the Stack2 to the return value;
3. Eject all data from the Stack2 to Stack1;
4. Return the return value
Code implementation
classsolution{ Public:voidPushintnode) {Stack1.push (node); }intPop () { while(!stack1.empty ()) {Stack2.push (Stack1.top ()); Stack1.pop (); }intnode = Stack2.top (); Stack2.pop (); while(!stack2.empty ()) {Stack1.push (Stack2.top ()); Stack2.pop (); }returnNode }Private: Stack<int>Stack1; Stack<int>Stack2;};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Sword means offer" with two stacks to implement a queue