- Implement Stack
中文English
Implement a stack. You can use any data structure inside a stack except stack itself to implement it.
Example
Example 1:
Input:
push(1)
pop()
push(2)
top() // return 2
pop()
isEmpty() // return true
push(3)
isEmpty() // return false
Example 2:
Input:
isEmpty()
解法1:用一个queue实现。
因为stack是后进先出,queue是先进先出,用queue实现stack的关键点就是
将front及其往后的N-1个元素重新放进queue,这样front元素就是最后一个元素了。
举例如下:
- empty
- push 1 (1) //front is 1
- push 2 (2, 1) -> requeue 1-> (1, 2)// front is 2
- push 3 (3, 1, 2) ->requeue 2, 1 -> (1,2,3) // front is 3
注意
- 这里是requeue N-1个,如果把N个元素全部requeue, 则上面第3步后就会变成(2, 1),front是1;第4步后会变成(3,2,1), front还是1。起不到stack的效果了
- 把for()放入pop()和top()是不对的,因为不知道top()和pop()谁先来,如果都放,则乱了。
- 该方法保证每次push前,queue里的元素都是按stack的后进先出顺序排放的。
- 该方法的push()慢,pop()和top()快,适合少push和多pop/top的操作。
代码如下:
class Stack {
public:
/*
* @param x: An integer
* @return: nothing
*/
void push(int x) {
q.push(x);
int N = q.size();
for (int i = 0; i < N - 1; ++i) {
q.push(q.front());
q.pop();
}
}
/*
* @return: nothing
*/
void pop() {
q.pop();
}
/*
* @return: An integer
*/
int top() {
return q.front();
}
/*
* @return: True if the stack is empty
*/
bool isEmpty() {
return q.empty();
}
private:
queue<int> q;
};
解法2:用两个queue(),把主要操作放到pop()和top()。
思路:以q1为主,q2为辅。每次push都push到q1中。
pop()时,将q1的从front往下的N-1个元素push到q2中然后pop,然后pop掉q1剩下的那个元素(即front),再将q1,q2交换。
top()时,将q1的从front往下的N-1个元素push到q2中然后pop,然后将q1剩下的那个元素(即front)赋给top,再把该元素push到q2中然后pop。再将q1,q2交换。返回top。
举例如下:
- empty q1: {}, q2: {}
- push 1 q1: (1) //q1.front is 1
- push 2 q1: (2, 1) //q1.front is 1
- push 3 q1: (3,2,1) //q1.front is 1
- top() q2: (3, 2,1), //q1.front is 1, return 3,swap q1, q2,最后q1: {3,2,1}, front 还是1, q2:{}
- pop() q2: {2,1} //q2.front is 1, q1 pop(), swap q1, q2,最后q1:{2,1}, q2: {}
代码如下:
class Stack {
public:
/*
* @param x: An integer
* @return: nothing
*/
void push(int x) {
q1.push(x);
}
/*
* @return: nothing
*/
void pop() {
int N = q1.size();
if (N > 1) {
for (int i = 0; i < N - 1; ++i) {
q2.push(q1.front());
q1.pop();
}
}
q1.pop();
swap(q1, q2);
}
/*
* @return: An integer
*/
int top() {
int N = q1.size();
if (N > 1) {
for (int i = 0; i < N - 1; ++i) {
q2.push(q1.front());
q1.pop();
}
}
int top = q1.front();
q1.pop();
q2.push(top);
swap(q1, q2);
return top;
}
/*
* @return: True if the stack is empty
*/
bool isEmpty() {
return q1.empty();
}
private:
queue<int> q1, q2;
};
该方法适合push()执行频率高而top()/pop()执行频率低的情况。
解法3:解法2的one queue版本
代码如下:
class Stack {
public:
/*
* @param x: An integer
* @return: nothing
*/
void push(int x) {
q.push(x);
}
/*
* @return: nothing
*/
void pop() {
int N = q.size();
if (N > 1) {
for (int i = 0; i < N - 1; ++i) {
q.push(q.front());
q.pop();
}
}
q.pop();
}
/*
* @return: An integer
*/
int top() {
int N = q.size();
if (N > 1) {
for (int i = 0; i < N - 1; ++i) {
q.push(q.front());
q.pop();
}
}
int top = q.front();
q.pop();
q.push(top);
return top;
}
/*
* @return: True if the stack is empty
*/
bool isEmpty() {
return q.empty();
}
private:
queue<int> q;
};