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. Tips:
Two stacks to implement a queue function? Ask for the algorithm and ideas!
< analysis;:
Queue: Put elements into Stack a
Out team: Determine if stack B is empty, if it is empty, then all elements of stack a POPs, and push into stack B, stack b out of the stack;
If not empty, stack B is directly out of the stack.
The ability to implement a stack with two queues? Ask for the algorithm and ideas!
< analysis;:
Into the stack: put elements into queue a
Stack: Determine whether the number of elements in queue A is 1, if equal to 1, or out of the queue, otherwise, the elements in queue a out of the queue and put in queue B, until one of the remaining elements in queue A, and then queue a out of the queue, and then put the elements in queue B out of queue a queue a.
Solution 1:
classsolution{ Public: voidPushintnode) {Stack1.push (node); } intpop () {if(Stack2.empty ()) { while(!Stack1.empty ()) { inttemp =Stack1.top (); Stack1.pop (); Stack2.push (temp); } } intresult =Stack2.top (); Stack2.pop (); returnresult; }Private: Stack<int>Stack1; Stack<int>Stack2;};Solution 2:
Using two stacks to implement a queue