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

LeetCode 232. Implement Queue using Stacks

2017-04-05 09:27 357 查看
题目:

Implement the following operations of a queue using stacks.

push(x) – Push element x to the back of queue.

pop() – Removes the element from in front of queue.

peek() – Get the front element.

empty() – Return whether the queue is empty.

Notes:

You must use only standard operations of a stack – which means only push to top, peek/pop from top, size, and is empty operations are valid.

Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.

You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

思路:

用两个栈实现队列,s1枯是队尾,s1的底是队头。在pop时,要借助s2,将s1的数都放到s2上,然后将s2的顶(即s1的底)pop; 取peek时,即将pop时的动作改为top即可;在push时,首先要将s2中的数再还原到s1,然后push;判断是否为empty要s1和s2都为empty时,队列才empty。

代码:

class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() {

}
/** Push element x to the back of queue. */
void push(int x) {
while (!s2.empty()){//如果s2不为空
s1.push(s2.top());//那就就先要将s2中的数据全都放到s1中
s2.pop();
}
s1.push(x);//入队列
}

/** Removes the element from in front of queue and returns that element. */
int pop() {
while (!s1.empty()){//如果s1不为空
s2.push(s1.top());//要将s1中的数据放到s2中,再取s2的栈顶元素s2.top()
s1.pop();//再pop
}
int result = s2.top();//出队列
s2.pop();
return result;
}

/** Get the front element. */
int peek() {
while (!s1.empty()){//如果s1不为空
s2.push(s1.top());//要将s1中的数据放到s2中,再取s2的栈顶元素s2.top()
s1.pop();//再pop
}
return s2.top();
}

/** Returns whether the queue is empty. */
bool empty() {
return s1.empty()&&s2.empty();//两个栈都为空时,队列才空
}
private:
stack<int> s1;
stack<int> s2;
};

/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* bool param_4 = obj.empty();
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: