您的位置:首页 > 产品设计 > UI/UE

[leetcode] 225. Implement Stack using Queues 解题报告

2015-12-28 17:20 555 查看
题目链接:https://leetcode.com/problems/implement-stack-using-queues/

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).

Update (2015-06-11):

The class name of the Java function had been updated to MyStack instead of Stack.

思路:可以用一个队列模拟一个栈

1. 对于top,我们知道栈是先入后出,因此top会返回最后一个入栈的值,而这个值在队列的尾部。而我们不能得到尾部的值,所以可以将队列前面的值出队列并将出队列的值加入队列尾中,而最后一个就是我们要的值。

2. 对于pop,和top的思想是一样的,只是剩下最后一个值将不入队列。

3. 对于push,直接入队列即可。

4. 对于empty,如果队列都为空,则栈为空,否则不为空。

代码如下:

class Stack {
public:
// Push element x onto stack.
void push(int x) {
que.push(x);
}

// Removes the element on top of the stack.
void pop() {
int k = que.size();
for(int i = 0; i< k-1; i++)
{
que.push(que.front());
que.pop();
}
que.pop();
}

// Get the top element.
int top() {
int k = que.size(), val;
for(int i = 0; i< k; i++)
{
if(i == k-1) val = que.front();
que.push(que.front());
que.pop();
}
return val;
}

// Return whether the stack is empty.
bool empty() {
return que.empty();
}
private:
queue<int> que;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: