7. queue with two stacks
Title Description
Two stacks to achieve a queue, the completion queue Push and Pop operations. Queue elements int.
Problem-solving ideas
- Stack: the stack is inserted into a
- The stack: Stack 2 determines whether the air
- Empty: Stack 1 elements of all pushed onto the stack 2
- Stack 2 Stack
[Image dump the chain fails, the source station may have security chain mechanism, it is recommended to save the picture down uploaded directly (img-pNrkex4T-1570784378627) (/ images / wins the offer / 7. .Png queue with two stacks)]
//.js
var stack1 = [];
var stack2 = [];
function push(node)
{
// write code here
stack1.push(node);
}
function pop()
{
// write code here
if(stack2.length == 0){
while(stack1.length > 0){
stack2.push(stack1.pop());
}
}
if(stack2.length >= 0){
return stack2.pop();
}
}
//.java
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
if (stack2.size() == 0) {
while (stack1.size() > 0) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}