admin管理员组文章数量:1636895
一天一道LeetCode
本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github
欢迎大家关注我的新浪微博,我的新浪微博
欢迎转载,转载请注明出处
(一)题目
Implement the following operations of a stack using queues.
- push(x) – Push element x onto stack.
- pop() – Removes the element on top of the stack.
- top() – Get the top element.
- empty() – Return whether the stack is empty.
Notes:
- You must use only standard operations of a queue – which means only push to back, peek/pop from front, size, and is empty operations are valid.
- Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
- You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack)
(二)解题
题目大意:用queue来实现一个stack。
解题思路:queue是先进先出,stack是先进后出。采用一个queue就能实现stack
push:直接压入到queue
pop:需要弹出queue的尾元素,可是queue只能弹出queue的头元素。这时候可以把queue的头元素弹出再压入queue,一直到尾元素弹出即可
top:直接利用queue的back()即可知道stack顶元素
empty:判断queue是否为空。
class Stack {
public:
// Push element x onto stack.
void push(int x) {
que.push(x);
}
// Removes the element on top of the stack.
void pop() {
int size = que.size();
for(int i = 0 ; i < size-1 ;i++){//queue的头元素弹出再压入,直到尾元素弹出
que.push(que.front());
que.pop();
}
que.pop();
}
// Get the top element.
int top() {
return que.back();
}
// Return whether the stack is empty.
bool empty() {
if(que.empty()) return true;
return false;
}
private:
queue<int> que;
};
本文标签: LeetCodeimplementqueuesStack
版权声明:本文标题:【一天一道LeetCode】#225. Implement Stack using Queues 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/xitong/1729235396a1191932.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论