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

225. Implement Stack using Queues

2016-07-05 22:13 281 查看
Implement the following operations of a stack using queues.

1.push(x) – Push element x onto stack.

2.pop() – Removes the element on top of the stack.

3.top() – Get the top element.

4.empty() – Return whether the stack is empty.

方法一:基本思路

跟之前那道反过来的题几乎一样,Implement Queue using Stack, 也就是按照stack的顺序在queue中强行排列,简单直接。

class Stack {
public:
// Push element x onto stack.
void push(int x) {
queue<int> temp;
while (!q.empty()) { //借用temp把queue里新push的值一直调到最顶端
temp.push(q.front());
q.pop();
}
q.push(x);
while (!temp.empty()) {
q.push(temp.front());
temp.pop();
}
}

// Removes the element on top of the stack.
void pop() {
q.pop();
}

// Get the top element.
int top() {
return q.front();
}

// Return whether the stack is empty.
bool empty() {
return q.empty();
}

private:
queue<int> q;
};


方法二:

换个新思路,方法一增加了push的复杂度。方法二增加了top, pop的复杂度,降低了push。

class Stack {
public:
// Push element x onto stack.
void push(int x) {
while (!q2.empty()) {
q1.push(q2.front());
q2.pop();
}
q2.push(x);//保持q2中只有一个元素,就是新增的元素。
}

// Removes the element on top of the stack.
void pop() {
top();
q2.pop();
}

// Get the top element.
int top() {
if (q2.empty()) {
for (int i = 0; i < q1.size() - 1; i++) {
q1.push(q1.front());
q1.pop();
}
q2.push(q1.front());
q1.pop();
}

4000
return q2.front(); //q2代表栈顶的元素,如果q2没有,则要在q1最下面把那个元素挑出来放进q2
}

// Return whether the stack is empty.
bool empty() {
return q1.empty() && q2.empty();
}

private:
queue<int> q1, q2;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: