[Offoffoffer] implements queues using two stacks, and offoffoffer implements queues.
Problem description:
Use two stacks to implement a queue and complete the Push and Pop operations of the queue. The element in the queue is of the int type.
Algorithm analysis:
Push:
1. Press data into stack1;
Pop:
1. pop up all data in stack1 to stack2;
2. Set the first number in stack2 to the returned value;
3. pop up all data in stack2 to stack1;
4. Return the returned value
Code Implementation
Class Solution {public: void push (int node) {stack1.push (node) ;}int pop () {while (! Stack1.empty () {stack2.push (stack1.top (); stack1.pop ();} int node = stack2.top (); stack2.pop (); while (! Stack2.empty () {stack1.push (stack2.top (); stack2.pop ();} return node;} private: stack <int> stack1; stack <int> stack2 ;};
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.