Article Directory
1. Title description
Use two stacks to implement a queue to complete the Push and Pop operations of the queue. The elements in the queue are of type int.
2. Analysis
The queue is: " first in first out "
stack is: " first in last out "
How to use two stations to implement a queue, see the two stacks in the following figure: in
and out
Illustration: Push operation directly to the in
middle, pop operation needs to be classified: if the out
stack is empty, then in
the data in the out
stack needs to be transferred to the stack, and then When out
popping the stack, if the out
stack is not empty, just pop directly.
3. Code implementation
3.1 Java implementation
import java.util.Stack;
public class JzOffer5 {
Stack<Integer> in = new Stack<Integer>();
Stack<Integer> out = new Stack<Integer>();
public void push(int node){
in.push(node);
}
public int pop(){
if (out.isEmpty()) {
while (!in.isEmpty()) {
out.push(in.pop());
}
}
return out.pop();
}
}
3.2 Python implementation
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack1 = []
self.stack2 = []
def push(self, node):
# write code here
self.stack1.append(node)
def pop(self):
# return xx
if len(self.stack2) == 0:
while len(self.stack1) != 0:
self.stack2.append(self.stack1.pop())
return self.stack2.pop()