用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
示例 1:
输入:
["CQueue","appendTail","deleteHead","deleteHead"]
[[],[3],[],[]]
输出:[null,null,3,-1]
示例 2:
输入:
["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
[[],[],[5],[2],[],[]]
输出:[null,-1,null,null,5,2]
链接:https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof
这道题是让用两个栈实现一个队列,队列的特点是先进先出,而栈的特点是先进后出,那么我们可以用一个栈来存数据,也就是入队的时候,加到一个栈里,然后出队的时候,如果此时两一个栈为空,那我们把第一个栈的数据放进第二个栈,否则就直接从第二个栈弹出数据,此时我们要注意的一点是,如果第一个和第二个栈都为空,那么返回-1;
代码如下:
class CQueue {
public:
CQueue() {
}
void appendTail(int value) {
s1.push(value);
}
int deleteHead() {
if(s2.empty())
{
if(s1.empty()) return -1;
while(!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
}
int res=s2.top();
s2.pop();
return res;
}
private:
stack<int> s1;
stack<int>s2;
};
/**
* Your CQueue object will be instantiated and called as such:
* CQueue* obj = new CQueue();
* obj->appendTail(value);
* int param_2 = obj->deleteHead();
*/
实现一个MyQueue类,该类用两个栈来实现一个队列。
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
代码如下:
class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
s1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int res=peek();
s2.pop();
return res;
}
/** Get the front element. */
int peek() {
if(s2.empty())
{
while(!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
}
return s2.top();
}
/** Returns whether the queue is empty. */
bool empty() {
if(s1.empty()&&s2.empty())
{
return true;
}
return false;
}
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();
*/
栈的最小值
请设计一个栈,除了常规栈支持的pop与push函数以外,还支持min函数,该函数返回栈元素中的最小值。执行push、pop和min操作的时间复杂度必须为O(1)。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
为了取得栈的最小值,我们可以借助一个辅助栈来存最小值,每次加入新的元素时,用新加入元素和当前辅助栈顶元素比较,用辅助栈来存当前的最小值,注意,当辅助栈为空时,直接加入元素
代码如下:
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
s1.push(x);
if(minS.empty())
{
minS.push(x);
}
else
{
minS.push(min(minS.top(),x));
}
}
void pop() {
s1.pop();
minS.pop();
}
int top() {
return s1.top();
}
int getMin() {
return minS.top();
}
private:
stack<int> s1;
stack<int> minS;
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/