[232] Implement Queue using Stacks
2016-07-21 12:46
441 查看
1. 题目描述
Implement the following operations of a queue using stacks.push(x) – Push element x to the back of queue.
pop() – Removes the element from in front of queue.
peek() – Get the front element.
empty() – Return whether the queue is empty.
Notes:
You must use only standard operations of a stack – which means only push to top, peek/pop from top, size, and is empty operations are valid.
Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
使用栈实现队列。只能使用栈提供的push, peek/pop, size和empty方法。
2. 解题思路
栈和队列不同的地方在于,栈为后进先出,而队列为先进先出。也就是说,对于一个栈,只能看到当前栈顶的元素,但是对于队列,我们要看到位于当前栈中最深处的元素。但是当我们把一个栈翻转过来,栈中最深处的元素就变成了当前栈顶元素,再顺序出栈就能达到队列的效果。所以想法就是使用两个栈,一个栈保存正序列元素,另一个栈用来翻转这些元素。入队操作只需要push到正序列元素中,出队操作则先将正序列元素进行反转,再输出最上面的元素即可。值得一提的是,当前翻转过的栈不为空时,如果将正序列翻转后push进来就打乱了原有栈的顺序,所以需要加一个判断,当当前翻转栈有元素时直接出队即可。3. Code
import java.util.Stack; class MyQueue { Stack<Integer> forwardStack = new Stack<>(); Stack<Integer> reverseStack = new Stack<>(); // Push element x to the back of queue. public void push(int x) { forwardStack.push(x); } // Removes the element from in front of queue. public void pop() { if(reverseStack.empty()) doReverse(); reverseStack.pop(); } // Get the front element. public int peek() { if(reverseStack.empty()) doReverse(); return reverseStack.peek(); } // Return whether the queue is empty. public boolean empty() { return forwardStack.size() == 0 && reverseStack.size() == 0; } /** * 翻转栈 */ private void doReverse() { while(!forwardStack.empty()) { reverseStack.push(forwardStack.pop()); } } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- 数据结构——栈与队列
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解