LeetCode---Implement Queue Using Stacks、Implement Stack Using Queues解题分析
2016-05-13 11:49
423 查看
题意描述:用两个栈来实现一个队列的操作,用两个队列来实现一个栈的操作
解题思路:
用栈实现队列的操作:栈S1、S2分别用于入队、出队
(1)入队:若S1不满直接将新元素放入S1,若S1满则将S1中元素转入S2,然后再将新元素放入S1;
(2)出队:若S2不空则直接从S2弹出栈顶元素,若S2空则先将S1元素转到S2再弹出S2栈顶元素;
用队列实现栈的操作:声明队列Q1、Q2
(1)入栈:若Q1有元素、Q2为空,则将新元素加入Q2,然后将Q1元素转入Q2中(反过来也可以,只需要保证一个队列为空即可);
(2)出栈:将有元素的队列输出即可;
解题思路:
用栈实现队列的操作:栈S1、S2分别用于入队、出队
(1)入队:若S1不满直接将新元素放入S1,若S1满则将S1中元素转入S2,然后再将新元素放入S1;
(2)出队:若S2不空则直接从S2弹出栈顶元素,若S2空则先将S1元素转到S2再弹出S2栈顶元素;
public class ImplementQueueUsingStacks { Stack<Integer> s1 = new Stack<>(); Stack<Integer> s2 = new Stack<>(); // Push element x to the back of queue. public void push(int x) { s1.push(x); } // Removes the element from in front of queue. public void pop() { if(!s2.isEmpty()) s2.pop(); else{ while(!s1.isEmpty()) s2.push(s1.pop()); s2.pop(); } } // Get the front element. public int peek() { if(!s2.isEmpty()) return s2.peek(); else{ while(!s1.isEmpty()) s2.push(s1.pop()); return s2.peek(); } } // Return whether the queue is empty. public boolean empty() { return s1.empty() && s2.empty(); } public static void main(String[] args) { ImplementQueueUsingStacks s = new ImplementQueueUsingStacks(); s.push(1); s.push(2); s.push(3); while(!s.empty()){ System.out.println(s.peek()); s.pop(); } } }
用队列实现栈的操作:声明队列Q1、Q2
(1)入栈:若Q1有元素、Q2为空,则将新元素加入Q2,然后将Q1元素转入Q2中(反过来也可以,只需要保证一个队列为空即可);
(2)出栈:将有元素的队列输出即可;
public class ImplementStackUsingQueues { // Push element x onto stack. Queue<Integer> q1 = new LinkedList<Integer>(); Queue<Integer> q2 = new LinkedList<Integer>(); public void push(int x) { q1.offer(x); } // Removes the element on top of the stack. public void pop() { while(q1.size()>1) q2.offer(q1.poll()); q1.poll(); Queue<Integer> q = q1; q1 = q2; q2 = q; } // Get the top element. public int top() { while(q1.size()>1) q2.offer(q1.poll()); int x = q1.poll(); q2.offer(x); Queue<Integer> q = q1; q1 = q2; q2 = q; return x; } // Return whether the stack is empty. public boolean empty() { return q1.isEmpty(); } public static void main(String[] args) { // TODO Auto-generated method stub } }
相关文章推荐
- UITableView-01初见
- Sequelize 事务大并发下造成的死锁问题。
- java execute、executeQuery和executeUpdate之间的区别
- UITextField常用属性及键盘收回的几种方式
- UE中使用正则表达式的一些技巧
- 【源代码】UITextView使用自定义微博表情键盘
- UI ID UE GUI 是什么?
- iOS获取UUID,并使用keychain存储
- UGUI batch 规则和性能优化
- ios开发--为UITextFieid设置编辑事件
- iOS自定义转场详解01——UIViewControllerTransitioning的用法
- ue4 服务器登陆流程
- iOS8新特性——UIPresentation在转场动画中的使用
- UIKit
- 从MIUI 1到MIUI 8 都有哪些变化?
- 关于.Net 中的 request.AllowAutoRedirect 属性(获取跳转后网页源码)
- UIAlertController的使用
- Android values-sw400dp 屏幕适配
- 开篇&TexturePacker打出图集给UGUI使用
- UIScreen的 bound、frame、scale属性