leetcode oj java Implement Queue using Stacks
来源:互联网 发布:四川移动网络加速器 编辑:程序博客网 时间:2024/05/17 21:39
一、问题描述:
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.
- 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).
二、思路:
两个栈存放数据。ST1 ST2
在放入数据(push)的时候压入栈1,
弹出数据的时候,如果栈2不为空,以此弹出栈1中的数据压入栈2,取栈2的最上边的数据
获得最前边的数据的时候,如果栈2不为空,以此弹出栈1中的数据压入栈2,取栈2的最上边的数据。
举例: push(1) , push(2) , pop() , push(3) , peek(), push(4), pop() , pop()
push(1) : 栈1的状态是 1 栈2是 null
push(2) : 栈1的状态是 1 2 栈2是 null
pop() : 栈1的状态是 null 栈2首先是 2 1 其次弹出1
push(3) : 栈1的状态是3 栈2是2
peek(3) : 栈1的状态是3 栈2是2 取出2
push(4) : 栈1的状态是3 4 , 栈2是2
pop(): 栈1的状态是3 4 , 栈2是null
pop(): 栈1的状态是null , 栈2是4 3 其次弹出3
三、代码
class MyQueue { Stack<Integer> st1 = new Stack<Integer>(); Stack<Integer> st2 = new Stack<Integer>(); public void push(int x) { st1.push(x); } // Removes the element from in front of queue. public void pop() { if(!st2.empty()){ st2.pop(); return ; } while(!st1.empty()){ int tmp = st1.peek(); st1.pop(); st2.push(tmp); } st2.pop(); } // Get the front element. public int peek() { if(!st2.empty()){ return st2.peek(); } while(!st1.empty()){ int tmp = st1.peek(); st1.pop(); st2.push(tmp); } return st2.peek(); } // Return whether the queue is empty. public boolean empty() { return st1.empty() && st2.empty(); }}
0 0
- leetcode oj java Implement Queue using Stacks
- <LeetCode OJ> 232. Implement Queue using Stacks
- 【LeetCode OJ 232】Implement Queue using Stacks
- Leetcode: 232. Implement Queue using Stacks(JAVA)
- leetcode :Implement Queue using Stacks
- [LeetCode] Implement Queue using Stacks
- LeetCode Implement Queue using Stacks
- LeetCode || Implement Queue using Stacks
- leetcode Implement Queue using Stacks
- Leetcode Implement Queue using Stacks
- [LeetCode]Implement Queue using Stacks
- 【Leetcode】Implement Queue using Stacks
- LeetCode Implement Queue using Stacks
- Leetcode: Implement Queue using Stacks
- [leetcode] Implement Queue using Stacks
- 【leetcode】Implement Queue using Stacks
- [Leetcode]Implement Queue using Stacks
- [leetcode] Implement Queue using Stacks
- Eclipse导出SVN项目的时候,不再提示输入用户名,密码问题
- 需求分析中原型化方法
- 6.2.4
- 纯Css实现三角形
- 快速幂
- leetcode oj java Implement Queue using Stacks
- 【深入Java字符串】(2)Java String案例分析
- Qt信号与槽的自动
- 稀疏自编码
- Java泛型真的是鸡肋吗?
- php中yii框中findOne()的用法
- Java之嵌套接口和嵌套类了解和简单实例
- inline-block和inline的区别
- JAVA面试题集锦01