GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — leetcode/src/ImplementQueueUsingStacks.java at master · LeBW/leetcode Expand file tree/ Copy pathImplementQueueUsingStacks.javaMore file actions 48 lines (43 loc) · 1.39 KB / Copy pathImplementQueueUsingStacks.javaFile metadata and controls48 lines (43 loc) · 1.39 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 import java.util.ArrayDeque; import java.util.Deque; /** * 232. Implement Queue Using Stacks * 两个栈,模拟队列 * 1. 入栈的时候全部入 stack1 * 2. 出栈的时候,看看 stack2 是不是空。如果是空的话,把 stack1 里的元素全部倒进去。然后从 stack2 里面输出一个元素。 * @author LBW */ public class ImplementQueueUsingStacks { Deque<Integer> firstStack; Deque<Integer> secondStack = new ArrayDeque<Integer>(); /** Initialize your data structure here. */ public ImplementQueueUsingStacks() { firstStack = new ArrayDeque<>(); } /** Push element x to the back of queue. */ public void push(int x) { firstStack.push(x); } /** Removes the element from in front of queue and returns that element. */ public int pop() { if (secondStack.isEmpty()) { while (!firstStack.isEmpty()) { secondStack.push(firstStack.pop()); } } return secondStack.pop(); } /** Get the front element. */ public int peek() { if (secondStack.isEmpty()) { while (!firstStack.isEmpty()) { secondStack.push(firstStack.pop()); } } return secondStack.peek(); } /** Returns whether the queue is empty. */ public boolean empty() { return firstStack.isEmpty() && secondStack.isEmpty(); } } |
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |