【leetcode】232. Implement Queue using Stacks
来源:互联网 发布:淘宝纸箱设备 编辑:程序博客网 时间:2024/06/05 04:15
一、题目描述
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).
题目解读:用堆栈实现队列的操作。堆栈只能使用标准的操作函数:添加元素push,移除函数pop,堆栈大小size,堆栈是否为空empty
思路:两个堆栈实现一个队列
(1)队列添加元素:进栈p1,
(2)队列删除元素:如果栈p2不空,直接删除p2的栈顶元素;如果栈p2空,先从p1把所有元素出栈进栈到p2,然后再删除p2的栈顶元素。
(3)返回队列队头元素:如果栈p2不空,直接返回p2的栈顶元素;如果栈p2空,先从p1把所有元素出栈进栈到p2,然后再返回p2的栈顶元素。
(4)判断队列是否为空:判断栈p1和p2是否为空。
c++代码(0ms,10.84%)
class Queue {public: stack<int> p1,p2; // Push element x to the back of queue. void push(int x) { p1.push(x); } // Removes the element from in front of queue. void pop(void) { if(p2.empty()){ while(!p1.empty()){ p2.push(p1.top()); p1.pop(); } } p2.pop(); } // Get the front element. int peek(void) { if(p2.empty()){ while(!p1.empty()){ p2.push(p1.top()); p1.pop(); } } return p2.top(); } // Return whether the queue is empty. bool empty(void) { return p1.empty() && p2.empty(); }};
0 0
- [LeetCode]232.Implement Queue using Stacks
- 【leetcode】232. Implement Queue using Stacks
- <LeetCode OJ> 232. Implement Queue using Stacks
- 232. Implement Queue using Stacks LeetCode
- Leetcode: 232. Implement Queue using Stacks(JAVA)
- 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
- #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
- 【leetcode】232. Implement Queue using Stacks
- [leetcode] 232. Implement Queue using Stacks
- LeetCode - 232. Implement Queue using Stacks
- Python学习笔记 20160615
- C#点击只打开一个窗体
- Cocos2d-Lua之函数
- uname命令的使用方法
- Akka学习笔记:Actor消息传递(1)
- 【leetcode】232. Implement Queue using Stacks
- 订阅模式(publish-subscribe)
- linux 容器(LXC) 第1章 LXC 简介
- vue 学习记录
- struts form样式怎么修改
- JAVA I/O流
- linux 容器(LXC) 第2章 chroot
- Linux下查看文件和文件夹大小
- 如何给UIView等控件用xib设置圆角属性