leetCode(37):Implement Queue using Stacks 分类: leetCode 2015-07-14 08:42 157人阅读 评论(0) 收藏
2015-07-14 08:42
453 查看
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
and
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).
两个栈,一个作为压入栈,一个作为弹出栈。当弹出栈为空时,把压入栈中的数据依次弹出并压入到弹出栈中。如果两者均为空,说明队列为空。
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,
and
is emptyoperations 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).
两个栈,一个作为压入栈,一个作为弹出栈。当弹出栈为空时,把压入栈中的数据依次弹出并压入到弹出栈中。如果两者均为空,说明队列为空。
class Queue { public: // Push element x to the back of queue. void push(int x) { push_stack.push(x); } // Removes the element from in front of queue. void pop(void) { if (pop_stack.empty()) { while (!push_stack.empty()) { pop_stack.push(push_stack.top()); push_stack.pop(); } if (!pop_stack.empty()) pop_stack.pop(); } else { pop_stack.pop(); } } // Get the front element. int peek(void) { if (pop_stack.empty()) { while (!push_stack.empty()) { pop_stack.push(push_stack.top()); push_stack.pop(); } if (!pop_stack.empty()) return pop_stack.top(); } else { return pop_stack.top(); } return 0; } // Return whether the queue is empty. bool empty(void) { if (pop_stack.empty() && push_stack.empty()) return true; else return false; } private: stack<int> pop_stack; stack<int> push_stack; };
相关文章推荐
- .NET平台开源项目速览(10)FluentValidation验证组件深入使用(二)
- iOS开发——UI基础-控制器,IBAction和IBOutlet,UIView
- [Leetcode 225, Easy] Implement Stack using Queues
- 动效:文字/UIView 从顶部下滑出现,然后滑回去
- 重踏学习Java路上_Day25(GUI)
- continue
- cpuinfo
- iOS KVC(Key-Value Coding)
- iOS中UIButton的使用
- ol元素及相关属性:type, start, value, 和rever
- Android开发UI之布局文件LinearLayout
- iOS中UITextField使用
- [扩展]为UIView扩展x,y,width,height,centerX,centerY,Size,Origin等属性
- UI_UItableView_AutoCell(自定义cell)
- 黑马程序员——基础学习(九)String的实际案例及StringBuffer/StringBuilder
- UIKit框架-07.UIAlertController使用
- [UI] 精美UI界面欣赏[12]
- UI--Android中的状态切换按钮自定义
- UIKit框架 - 06.UIActionSheet使用
- vs2013错误,错误 1 error MSB8020: The build tools for Visual Studio 2012