题目
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).
题意
用队列实现栈的操作。
- push(x) – 进栈.
- pop() – 出战.
- top() – 获取栈顶元素.
- empty() – 判断栈是否为空.
Notes:
- 您必须只使用队列的标准操作——这意味着只有从前到后、从前端到大小,以及空操作都是有效的。.
- 这取决于你的语言,可能不支持本地队列。你可以通过使用列表或队列模拟一个队列(双端队列),只要你只使用一个队列的标准操作.
- 您可以假设所有操作都是有效的(例如,在空堆栈上不会调用POP或顶级操作)。 .
题解
queue 的基本操作有:
操作 | 说明 |
---|---|
q.push(x) | 入队, 将x 接到队列的末端 |
q.pop() | 出队,弹出队列的第一个元素,注意,并不会返回被弹出元素的值 |
q.front() | 访问队首元素, 即最早被压入队列的元素。 |
q.back() | 访问队尾元素, 即最后被压入队列的元素 |
q.empty() | 判断队列空,, 当队列空时,返回true |
q.size() | 访问队列中的元素个数 |
栈的特点是:先进后出
队列的特点是:先进先出
思路:把队列中的元素转换成栈操作的顺序
例如 :
栈中 1 2 3,出栈为 3 2 1
队列中1 2 3, 出队 1 2 3
如果队列中元素为 3 2 1, 出队3 2 1
如何转换:
每在队列中添加一个元素,转换一次,具体见代码
C++代码
class MyStack {
public:
/** Initialize your data structure here. */
queue<int>q;
queue<int>temp;
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
q.push(x);
for(int i=0; i<q.size()-1; i++)//把前n-1个依次放在队尾
/*
例如 队列中现在的元素为 1 2
添加元素3 为 3 1 2
将前2个元素依次放在队尾
即1 2 3
*/
{
q.push(q.front());
q.pop();
}
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int m = q.front();
q.pop();
return m;
}
/** Get the top element. */
int top() {
return q.front();
}
/** Returns whether the stack is empty. */
bool empty() {
return q.empty();
}
};
python代码
python中的队列的详细用法:
https://www.cnblogs.com/cmnz/p/6936181.html
http://python.jobbole.com/87577/
from collections import deque
class MyStack:
def __init__(self):
self.q = deque();
def push(self, x):
self.q.append(x)
for i in range(0, len(self.q)-1):
self.q.append(self.q.popleft())
#q.popleft()删除栈顶元素并返回此元素值
def pop(self):
return self.q.popleft()
def top(self):#返回栈顶元素
return self.q[0]
def empty(self):
return len(self.q)==0