LeetCode 232 Implement Queue using Stacks
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 232: Implement Queue using Stacks
[Leetcode] 232. Implement Queue using Stacks
leetcode 232. Implement Queue using Stacks
LeetCode 232 Implement Queue using Stacks