Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
implement-stack-using-queues.cpp 1.24 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2016-04-29 00:22 +08:00 . Update implement-stack-using-queues.cpp
// Time: push: O(n), pop: O(1), top: O(1)
// Space: O(n)
class Stack {
public:
queue<int> q_;
// Push element x onto stack.
void push(int x) { // O(n)
q_.emplace(x);
for (int i = 0; i < q_.size() - 1; ++i) {
q_.emplace(q_.front());
q_.pop();
}
}
// Remove the element on top of the stack.
void pop() { // O(1)
q_.pop();
}
// Get the top element.
int top() { // O(1)
return q_.front();
}
// Return whether the stack is empty.
bool empty() { // O(1)
return q_.empty();
}
};
// Time: push: O(1), pop: O(n), top: O(1)
// Space: O(n)
class Stack2 {
public:
queue<int> q_;
int top_;
// Push element x onto stack.
void push(int x) { // O(1)
q_.emplace(x);
top_ = x;
}
// Remove the element on top of the stack.
void pop() { // O(n)
for (int i = 0; i < q_.size() - 1; ++i) {
top_ = q_.front();
q_.emplace(top_);
q_.pop();
}
q_.pop();
}
// Get the top element.
int top() { // O(1)
return top_;
}
// Return whether the stack is empty.
bool empty() { // O(1)
return q_.empty();
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助