这里选择了一些栈和队列的练习,一部分来自leetcode,也有一部分通过vjudge
取自其他平台。没有选择综合性较强的题目,单纯使用栈、队列、线性表的基本操作和思想就可以解决了。
对于双端队列和优先队列,这里仅仅使用STL进行解决,说明一下使用他们进行解决的办法,不提及物理实现及相关问题。双端队列的物理实现可以使用带尾结点的链表;而优先队列需要使用二叉堆(binary heap)实现,这在第10章内排序再写总结。
用栈实现队列(Implement Stack using Queues)
需要使用栈完成一个队列,队列支持如下操作:
操作 | 描述 |
---|---|
push(x) |
将x进入队列 |
pop() |
将队首元素出列 |
peek() |
返回队首元素 |
empty() |
判断队列是否为空 |
要求只能使用基本的栈操作(push
、pop
、empty
、top
)。
栈是LIFO特性,而队列是FIFO特性。也就是说队列的出列,实际上要取栈底元素。因此这里可以使用两个栈来完成,需要取栈底元素,只需要将所有元素放入第二个栈,取其
栈顶就可以了。
参考解答:
class MyQueue {
public:
stack<int> st1, st2;
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
st1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
while(!st1.empty()){
st2.push(st1.top());
st1.pop();
}
int result = st2.top();
st2.pop();
while(!st2.empty()){
st1.push(st2.top());
st2.pop();
}
return result;
}
/** Get the front element. */
int peek() {
while(!st1.empty()){
st2.push(st1.top());
st1.pop();
}
int result = st2.top();
while(!st2.empty()){
st1.push(st2.top());
st2.pop();
}
return result;
}
/** Returns whether the queue is empty. */
bool empty() {
return st1.empty();
}
};
用队列实现栈(Implement Stack using Queues )
需要使用队列完成一个栈,栈支持如下操作:
操作 | 描述 |
---|---|
push(x) |
将x入栈 |
pop() |
将栈顶元素出栈 |
top() |
返回栈顶元素 |
empty() |
判断栈是否为空 |
要求只能使用基本的队列操作(push
、pop
、empty
、front
)。
和上一道题较为类似,一样需要处理LIFO和FIFO的关系。也需要使用两个队列,取最后元素时,则已经取出的元素的个数总是比总数少1。将第二个队列作为临时空间,同时维护一个计数器就可以了。
class MyStack {
public:
queue<int> qu1;
queue<int> qu2;
int ptr;
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
qu1.push(x);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int counter = 0;
while(!qu1.empty()){
qu2.push(qu1.front());
qu1.pop();
counter++;
}
counter--; //将计数器自减,以便于取出队尾元素
while(counter > 0){
qu1.push(qu2.front());
qu2.pop();
counter--;
}
int result = qu2.front();
qu2.pop();
return result;
}
/** Get the top element. */
int top() {
int counter = 0;
while(!qu1.empty()){
qu2.push(qu1.front());
qu1.pop();
counter++;
}
counter--;
while(counter > 0){
qu1.push(qu2.front());
qu2.pop();
counter--;
}
int result = qu2.front();
qu2.pop();
qu1.push(result);
return result;
}
/** Returns whether the stack is empty. */
bool empty() {
return qu1.empty();
}
};
最小栈(Min Stack)
要求设计一个栈,除了支持最基本的栈操作,还需要支持在 O(1)