232用栈实现队列

使用栈实现队列的下列操作:

push(x) -- 将一个元素放入队列的尾部。
pop() -- 从队列首部移除元素。
peek() -- 返回队列首部的元素。
empty() -- 返回队列是否为空。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-queue-using-stacks

 1 import java.util.Stack;
 2 
 3 public class StackForQueue {
 4     private Stack<Integer> outStack = new Stack<>();
 5     private Stack<Integer> 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 }
无论有多困难,都坚强的抬头挺胸,人生是一场醒悟,不要昨天,不要明天,只要今天。不一样的你我,不一样的心态,不一样的人生,顺其自然吧
原文地址:https://www.cnblogs.com/xiyangchen/p/11173659.html