版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014303647/article/details/88557079
Leetcode 232. Implement Queue using Stacks 用队列实现栈
Leetcode225. Implement Stack using Queues 用栈实现队列
首先我们得知道队列和栈的性质。
队列:先进先出。
栈:先进后出。
所以怎么用栈实现队列呢
怎么实现先进先出呢?用一个栈肯定是无法实现的,因为栈只有一个开口,所以可以使用两个栈。
一个作为数据存储,一个作为中转栈。
然后队列的基本操作:
1:queue.push()
2: queue.pop()
3: queue.peek()
4: queue.empty()
怎么实现push呢?首先肯定压入第一个元素时,data栈为空,直接压入,但是也用可能经过若干次步骤,我们中转栈里还有元素,那么我们比如先把中转栈里元素转回去,然后最后将x入栈
pop:因为队列是先进先出,所以要pop的元素必定在栈底,所以将data里的元素转到temp里,那么现在的栈顶元素就会最开始的那个元素
peek:如果中转栈temp不为空,那么栈顶元素就为队首元素。
empty:如果数据站和中转栈都为空,则队列为空。
为什么每次pop以后,不把中转栈的元素重新压入原始栈data呢?因为可能要继续pop,所以这样做了一点优化。
代码:
class MyQueue
{
public:
/** Initialize your data structure here. */
MyQueue()
{
while(!data.empty()) data.pop();
while(!temp.empty()) temp.pop();
}
/** Push element x to the back of queue. */
void push(int x)
{
while(!temp.empty())
{
int y = temp.top();
temp.pop();
data.push(y);
}
data.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop()
{
int x;
if(!temp.empty())
{
x = temp.top();
temp.pop();
return x;
}
else
{
while(!data.empty())
{
x = data.top();
data.pop();
temp.push(x);
}
x = temp.top();
temp.pop();
return x;
}
}
/** Get the front element. */
int peek()
{
if(!temp.empty()) return temp.top();
else
{
while(!data.empty())
{
int x = data.top();
data.pop();
temp.push(x);
cout << x << endl;
}
return temp.top();
}
}
/** Returns whether the queue is empty. */
bool empty()
{
if(data.empty() && temp.empty()) return true;
return false;
}
stack<int> data;
stack<int> temp;
};
/**
* 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();
*/
怎么用队列实现栈呢?
栈的性质是先进后出。
那么我们每次入队以后,一次循环把size-1个元素放到队尾,这样就和栈里的顺序一模一样。
代码:
class MyStack
{
public:
queue<int> Q;
/** Initialize your data structure here. */
MyStack()
{
while(!Q.empty()) Q.pop();
}
/** Push element x onto stack. */
void push(int x)
{
Q.push(x);
int size = Q.size();
for(int i = 0; i < size-1; i++)
{
int y = Q.front();
Q.pop();
Q.push(y);
}
}
/** Removes the element on top of the stack and returns that element. */
int pop()
{
int x = Q.front();
Q.pop();
return x;
}
/** Get the top element. */
int top()
{
return Q.front();
}
/** Returns whether the stack is empty. */
bool empty()
{
if(Q.size()==0) return true;
return false;
}
};
/**
* 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();
*/