使用一个队列
class MyStack {
public:
//单链表实现
//在栈中元素的顺序应该是和队列中的顺序相反的,因此整体的思路是元素插入后,将插入元素之前的所有元素出队列重新入队列,这样就可以吧顺序调转过来,这样元素的顺序就一致了,栈中的其他操作就和队列中的操作一致了。时间复杂度为O(n)。
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
q.push(x);
int sz = q.size();
while(sz>1) //把插入元素之前的所有元素出队列在入队列。
{
q.push(q.front());
q.pop();
sz--;
}
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int tmp = q.front();
q.pop();
return tmp;
}
/** Get the top element. */
int top() {
return q.front();
}
/** Returns whether the stack is empty. */
bool empty() {
return q.empty();
}
private:
queue<int> q;
};
使用两个队列
class MyStack2 {
//双队列实现栈
//主要思路类似于一个队列的实现,有一个空队列负责插入元素,插入后,将另一个队列中的所有元素出队列然后入新队列,这样实现的顺序的反转,然后两个队列互相交换。保证q2是空队列,q1是存放元素队列。时间复杂度O(n)。相比于一个队列的方法,这种方式占用资源较多,因此通常使用一个队列就够了。
public:
/** Initialize your data structure here. */
MyStack2() {
}
/** Push element x onto stack. */
void push(int x) {
q2.push(x);
while(!q1.empty())
{
q2.push(q1.front());
q1.pop();
}
queue<int> temp = q1;
q1=q2;
q2=temp;
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int val = q1.front();
q1.pop();
return val;
}
/** Get the top element. */
int top() {
return q1.front();
}
/** Returns whether the stack is empty. */
bool empty() {
return q1.empty();
}
private:
queue<int> q1;
queue<int> q2;
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/
222

被折叠的 条评论
为什么被折叠?



