程序员面试金典-面试题 03.04. 化栈为队
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了程序员面试金典-面试题 03.04. 化栈为队,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1693字,纯文字阅读大概需要3分钟。
内容图文
题目:
实现一个MyQueue类,该类用两个栈来实现一个队列。
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
说明:
你只能使用标准的栈操作 -- 也就是只有 push to top, peek/pop from top, size 和 is empty 操作是合法的。
你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。
分析:
利用双栈实现一个队列,因为栈的出栈顺序和队列的出栈顺序正好相反,那么我们可以再用一个栈,当需要弹出队列时,将栈内的元素依次弹出加入到新的栈中,此时新栈的出栈顺序就和队列要求的出栈顺序相同了。注意只有在出队栈为空时,才进行转入操作。
程序:
class MyQueue { /** Initialize your data structure here. */ public MyQueue() { pushStack = new Stack<Integer>(); popStack = new Stack<Integer>(); } /** Push element x to the back of queue. */ public void push(int x) { pushStack.push(x); } /** Removes the element from in front of queue and returns that element. */ public int pop() { if(popStack.isEmpty()){ while(!pushStack.isEmpty()){ popStack.push(pushStack.pop()); } } return popStack.pop(); } /** Get the front element. */ public int peek() { if(popStack.isEmpty()){ while(!pushStack.isEmpty()){ popStack.push(pushStack.pop()); } } return popStack.peek(); } /** Returns whether the queue is empty. */ public boolean empty() { return pushStack.isEmpty() && popStack.isEmpty(); } private Stack<Integer> pushStack; private Stack<Integer> popStack; } /** * Your MyQueue object will be instantiated and called as such: * MyQueue obj = new MyQueue(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.peek(); * boolean param_4 = obj.empty(); */
内容总结
以上是互联网集市为您收集整理的程序员面试金典-面试题 03.04. 化栈为队全部内容,希望文章能够帮你解决程序员面试金典-面试题 03.04. 化栈为队所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。