使用栈实现队列的下列操作:
push(x) -- 将一个元素放入队列的尾部。
pop() -- 从队列首部移除元素。peek() -- 返回队列首部的元素。empty() -- 返回队列是否为空。来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-queue-using-stacks1 import java.util.Stack; 2 3 public class StackForQueue { 4 private StackoutStack = new Stack<>(); 5 private Stack inStack = new Stack<>(); 6 public StackForQueue() { 7 8 } 9 10 public void push(int x) {11 inStack.push(x);12 }13 14 public int pop() {15 if(outStack.isEmpty()) {16 while(!inStack.isEmpty()) {17 outStack.push(inStack.pop());18 } 19 }20 return outStack.pop();21 }22 23 public int peek() {24 if(outStack.isEmpty()) {25 while(!inStack.isEmpty()) {26 outStack.push(inStack.pop());27 } 28 }29 return outStack.peek();30 }31 32 public boolean empty() {33 return inStack.isEmpty() && outStack.isEmpty();34 }35 }