Recently in the brush "sword refers to offer" in the programming problem, but the internet about "sword refers to offer" solution is mostly C or C + +, and the official (author) is also in C + + to explain, here himself with Java wrote some of the answer code of the topic (of course, there are also some of the answers to the online others, The source does not indicate please point out, the invasion of the deletion, hope to be able to help everyone's study.
Topic:
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.
In fact, is the queue normal into the stack, the stack when the contents of the stack in order to move to another stack, negative negative positive, so again in order out of the stack, became the stack before the order of the queue
Import Java.util.Stack; Use the stack remember to refer to the Java.util,stack package public
class Solution {
stack<integer> stack1 = new stack<integer> ();
stack<integer> Stack2 = new stack<integer> ();
into the stack function public
void push (int num) {
stack1.push (num); What to push into the stack directly with the stack of the pushed method is good
//out of the stack function public
int pop () {
Integer re=null;
if (!stack2.empty ()) { //if stack 2 is not empty, then take out the topmost one
re=stack2.pop ();
} else{
//If stack 2 is empty, take out the number of stacks 1, and put it in the stack 2 while
(!stack1.empty ()) {
re=stack1.pop ();
Stack2.push (re);
After a number in the Stack 2, again take the inside number out
if (!stack2.empty ()) {
re=stack2.pop ();
}
}
return re;
}
}