C++中的Stack:
-
不支持iterator
-
不是container,而是container adapter
-
底层实现:vector, deque, list都可以,比如:
std::stack<int, std::vector<int> > third; // 使用vector为底层容器的栈
1.Implement Queue using Stacks
没想出来的题,stack和queue的题就是我的克星…
class MyQueue {
private:
stack<int> instack, outstack;
void revert(){
while(!instack.empty()){
outstack.push(instack.top());
instack.pop();
}
}
public:
MyQueue() {}
void push(int x) {
instack.push(x);
}
int pop() {
if(outstack.empty()){
revert();
}
int x = outstack.top();
outstack.pop();
return x;
}
int peek() {
if(outstack.empty()){
revert();
}
return outstack.top();
}
bool empty() {
return instack.empty() && outstack.empty();
}
};
2.Implement Stack using Queues
过年了有点想摆烂,用一个queue的办法不想想了。简单来讲,就是把新元素加到queue的尾部,大差不离。
class MyStack {
private:
queue<int> q1, q2;
void reload(){
while(!q2.empty()){
q1.push(q2.front());
q2.pop();
}
}
public:
MyStack() {}
void push(int x) {
q1.push(x);
}
int pop() {
int x;
while(!q1.empty()){
x = q1.front();
q1.pop();
if(!q1.empty()) q2.push(x);
}
reload();
return x;
}
int top() {
int x = pop();
q1.push(x);
return x;
}
bool empty() {
return q1.empty();
}
};
文章介绍了如何在C++中使用Stack和Queue来实现其他数据结构。具体包括用两个Stack实现Queue,以及用Queue实现Stack。关键操作如push、pop、peek和empty都在各自的实现中得到了详细解释。
558

被折叠的 条评论
为什么被折叠?



