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.
When the push function is executed, the value is put into Stack1, when the pop function is executed, the Stack2 is determined to be empty, the value of Stack1 is all put into stack2 when empty, and the Stack2 element is not required when it is not empty.
Class solution
{public
:
void push (int node) {
Stack1.push (node);
}
int pop () {
int value =-1;
if (Stack2.empty ())
{
while (!stack1.empty ())
{
Stack2.push (stack1.top ());
Stack1.pop (); Don't forget to eject the value in the stack after inserting
}
if (!stack2.empty ())
{
value = Stack2.top ();
Stack2.pop ();
}
return value;
}
Private:
stack<int> stack1;
Stack<int> stack2;
};
How to implement the stack with two queues to complete the push and pop operations of the stack. The elements in the stack are of type int.
When you execute the push function, the values are placed directly into queue1. When executing the POP function, there are three cases: the first case, to determine whether the queue1 is empty, is empty, you need to put the value of queue2 into Queue1, the last value pops up, the second case, whether the queue1 length is 1, 1 o'clock, the value of the queue1 is directly ejected In the third case, when the queue1 value is greater than 1 o'clock, the value of queue1 is moved directly into the queue2, leaving the last value and ejecting the value.
class solution {public:void push (int node) {Queue1.push (node);
} int pop () {int value =-1;
if (queue1.size () = = 0)//When queue1 is empty, move the value of queue2 directly into Queue1, retain the last value, and delete the value {if (queue2.size () = = 0) return value;
while (Queue2.size () > 1) {queue1.push (Queue2.front ());
Queue2.pop ();
} value = Queue2.front;
Queue2.pop ();
} else if (queue1.size () = = 1)//When queue1 length is 1 o'clock, remove the value of queue1 directly {value = Queue1.front ();
Queue1.pop ();
} else{//When the queue1 value is greater than 1 o'clock, move the value of queue1 directly into Queue2, retain the last value, and delete the value while (Queue1.size () > 1) {
Queue2.push (Queue1.front ());
Queue1.pop ();
} value = Queue1.front;
Queue1.pop ();
} return value;
} private:queue<int> queue1;
Queue<int> queue2; };