1、用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )来源:力扣(LeetCode)
解题思路:用两个栈一个用于添加一个用于删除。
1:定义两个栈分别为push和pop
1.1 push栈用于添加入队,pop栈用于出队,每次添加的时候最后添加的元素在push栈的栈顶,每次删除的时候要删除的元素在pop栈的栈顶。
1.2在删除队列元素的时候首先判定pop栈是否为空,如果为空将push栈内的元素转移到pop栈中(将push栈内的元素一次弹出一个再压入pop栈中),此时栈顶正好为队列的头,删除的时候只要删除pop栈的栈顶元素即可。
代码如下:
#include <stack>
#include <iostream>
using namespace std;
class CQueue {
public:
CQueue() {
m_push = new stack<int>;
m_pop = new stack<int>;
}
void appendTail(int value) {
m_push->push(value);
}
int deleteHead() {
if (m_pop->empty())
{
if (m_push->empty())
{
return -1;
}
while (!m_push->empty())
{
m_pop->push(m_push->top());
m_push->pop();
}
}
int num = m_pop->top();
m_pop->pop();
return num;
}
private:
stack<int>* m_push;
stack<int>* m_pop;
};
2、定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。来源:力扣(LeetCode)
解题思路:运用辅助栈存储当前知道的最小元素在辅助栈的栈顶中,对栈进行增加和删除的时候对辅助栈的栈顶元素进行判断,如果比当前栈顶元素小,则把当前栈顶元素添加进去,如果大于等于当前栈顶元素,则把栈顶元素重复添加入辅助栈。
2.1 将元素添加入栈,判断添加元素大小对min栈添加的元素进行选择
2.2 top返回stack栈顶元素,min返回min栈顶元素。
代码如下:
#include <stack> #include <iostream> using namespace std; class MinStack { public: /** initialize your data structure here. */ MinStack() { m_Stack = new std::stack<int>; m_Min = new std::stack<int>; } void push(int x) { m_Stack->push(x); if (m_Min->empty() == 1 || m_Min->top() > x) { m_Min->push(x); }else if (m_Min->top() < x) { m_Min->push(m_Min->top()); } } void pop() { m_Min->pop(); m_Stack->pop(); } int top() { return m_Stack->top(); } int min() { return m_Min->top(); } private: std::stack<int> *m_Stack; std::stack<int>* m_Min; }; int main() { MinStack Test; Test.push(NULL); Test.push(-2); Test.push(0); Test.push(-3); cout << Test.min() << endl; Test.pop(); cout << Test.top() << endl; cout << Test.min() << endl; return 0; }