栈和队列在STL中都不是容器,而是容器适配器。
栈和队列提供push 和 pop 等接口,但不提供迭代器(iterator)。 不像是set 或者map 提供迭代器iterator来遍历所有元素。
1. 用栈实现队列
题目:使用栈实现队列的下列操作:
push(x) – 将一个元素放入队列的尾部。
pop() – 从队列首部移除元素。
peek() – 返回队列首部的元素。
empty() – 返回队列是否为空。
输入:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 1, 1, false]
解释:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false
思路:两个栈实现,一个输入栈,一个输出栈。
抽象为:从水壶中倒水到A杯子,再从A杯倒入B杯,最后从B杯倒出。
但注意:pop时有两种情况
- 栈B非空,则先从栈B弹出数据。
- 栈B为空,则把A中数据全部导入B中,再pop。
笔记:C++ stack和queue中pop()
函数返回值都是void,注意:该题要求pop()还要返回值,略有不同。
在peek()
中可以复用pop()
,不然对对stOut判空的逻辑又要重写一遍。但记得pop()完还要把他push()进去。
Python中栈用list来表示。
关于C++ this指针:
this 是 C++ 中的一个关键字,也是一个 const 指针,它指向当前对象,通过它可以访问当前对象的所有成员。即this 指针是所有成员函数的隐含参数。类似于Python中的self,只不过self是显式的。
this 只能用在类的内部,通过 this 可以访问类的所有成员,包括 private、protected、public 属性的。
注意,友元函数没有 this 指针,因为友元不是类的成员,只有成员函数才有 this 指针。
C++:
class MyQueue {
public:
stack<int> stIn;
stack<int> stOut;
MyQueue() {}
void push(int x) {
stIn.push(x);
}
int pop() {
if(stOut.empty()){
// 若输出栈为空,则要将输入栈中值全部压入输出栈,再取顶一个元素,所以要用while
while(!stIn.empty()){
// 注意:C++ stack中,pop()是没有返回值的,所以这里改用top():取栈顶元素,后再pop()删除
stOut.push(stIn.top());
stIn.pop();
}
}
int result = stOut.top();
stOut.pop();
return result;
}
int peek() {
int res = this->pop();
stOut.push(res);
return res;
}
bool empty() {
return stIn.empty() && stOut.empty();
}
};
Python:
class MyQueue:
def __init__(self):
self.stack_in = []
self.stack_out = []
def push(self, x: int) -> None:
self.stack_in.append(x)
def pop(self) -> int:
if self.empty():
return None
if self.stack_out:
return self.stack_out.pop()
else:
for i in range(len(self.stack_in)):
self.stack_out.append(self.stack_in.pop())
return self.stack_out.pop()
def peek(self) -> int:
res = self.pop()
self.stack_out.append(res)
return res
def empty(self) -> bool:
return not (self.stack_in or self.stack_out)
2. 用队列实现栈
题目:使用队列实现栈的下列操作:
push(x) – 元素 x 入栈
pop() – 移除栈顶元素
top() – 获取栈顶元素
empty() – 返回栈是否为空
输入:
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 2, 2, false]
解释:
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // 返回 2
myStack.pop(); // 返回 2
myStack.empty(); // 返回 False
思路:有两种思路,两个队列和一个队列。这里先实现一个队列的。
pop()
时将除最后一个元素的其他元素重新添加到队尾,再pop()
就是栈的顺序了。
C++:
class MyStack {
public:
queue<int> que;
MyStack() {}
void push(int x) {
que.push(x);
}
int pop() {
int size = que.size();
size--; //除最后一个元素
while(size--){
que.push(que.front());
que.pop();
}
int result = que.front();
que.pop();
return result;
}
int top() {
return que.back(); // 返回队列的最后一个元素
}
bool empty() {
return que.empty();
}
};
Python:
class MyStack:
def __init__(self):
self.que = deque()
def push(self, x: int) -> None:
self.que.append(x)
def pop(self) -> int:
if self.empty():
return None
for i in range(len(self.que) - 1):
self.que.append(self.que.popleft())
return self.que.popleft()
def top(self) -> int:
if self.empty():
return None
return self.que[-1] # 返回队尾元素
def empty(self) -> bool:
return not self.que