首页 > 代码库 > LeetCode 232 Implement Queue using Stacks
LeetCode 232 Implement Queue using Stacks
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
, andis 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).
- You must use only standard operations of a stack -- which means only
思路:
利用两个栈,每次入队的操作时,将一个栈中的元素全部弹出,后在有元素的栈中压入入队元素,后将该栈的全部元素弹出,压回第一个栈中即可。
解法:
1 import java.util.Stack; 2 3 public class MyQueue 4 { 5 private Stack<Integer> inputStack; 6 private Stack<Integer> outputStack; 7 8 public MyQueue() 9 {10 inputStack = new Stack<>();11 outputStack = new Stack<>();12 }13 14 public void push(int x)15 {16 while(!outputStack.isEmpty())17 inputStack.push(outputStack.pop());18 inputStack.push(x);19 while(!inputStack.isEmpty())20 outputStack.push(inputStack.pop());21 }22 23 public void pop()24 { outputStack.pop(); }25 26 public int peek()27 { return outputStack.peek(); }28 29 public boolean empty()30 { return outputStack.isEmpty(); }31 }
LeetCode 232 Implement Queue using Stacks
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。