1. 實現一個棧,要求實現出棧,入棧,Min返回最小值的操作的時間復雜度為o(1)
思路:要使這些操作的時間復雜度為o(1),則必須保證棧的每個元素只被遍歷一次。求解時需要借助兩個棧,一個入數據,一個入所遍歷過數據的最小值,遍歷結束后,放最小值的棧的棧頂元素即為所求的最小值。
#include<iostream>
using namespace std;
#include<stack>
#include<assert.h>
#define capacity 10
template<class T>
class StackWithMin
{
public:
void Push(const T&value)
{
m_data.push(value);
if (m_min.size() == 0 || value < m_min.top())
m_min.push(value);
else
m_min.push(m_min.top());
}
void Pop()
{
assert(m_data.size >0 && m_min.size() > 0);
m_data.pop();
m_min.pop();
}
T Min()const
{
assert(m_data.size() >0 && m_min.size() > 0);
return m_min.top();
}
private:
stack<T> m_data; //數據棧
stack<T> m_min; //最小的數據棧
};
//測試
void main()
{
StackWithMin<int> st;
st.Push(9);
st.Push(2);
st.Push(6);
st.Push(4);
st.Push(3);
cout << st.Min() << endl;
}
2.用兩個棧實現一個隊列
思路:定義兩個棧st1,st2,st1棧專門入數據,st2棧專門出數據。無論st1有沒有數據直接入數據,如果st2有數據則出數據,沒有數據則將st1的數據“倒入”st2中
#include<iostream>
using namespace std;
#include<stack>
template<class T>
class CQueue
{
public:
void appendTail(const T&x) //從隊尾插入數據
{
st1.push(x);
}
T deleteHead() //刪除頭結點
{
if (st2.size() <= 0)
{
while (!st1.empty())
{
T value=st1.top();
st1.pop();
st2.push(value);
}
}
if (st2.size() > 0)
{
T head = st2.top();
st2.pop();
return head;
}
}
private:
stack<T> st1;
stack<T> st2;
};
//測試
void main()
{
CQueue<int> cq;
cq.appendTail(1);
cq.appendTail(2);
cq.appendTail(3);
cq.appendTail(4);
cout << cq.deleteHead() << endl;
}
3.用兩個隊列實現一個棧
思路:一個隊列q1專門負責入數據,只要有數據就入,將隊列q1中的元素入到輔助隊列q2中,直到q1中只剩下最后一個元素,將這個元素出隊列,即實現了出棧
#include<iostream>
using namespace std;
#include<queue>
template<class T>
class CStack
{
public:
void appendHead(const T&x) //從棧頂插入元素
{
q1.push(x);
}
T deleteTail() //從棧頂刪除元素
{
if (q2.size() <= 0)
{
while (q1.size()-1)
{
T value = q1.front();
q1.pop();
q2.push(value);
}
}
T tail = q1.front();
q1.pop();
return tail;
}
private:
queue<T> q1;
queue<T> q2;
};
//測試
void main()
{
CStack<int> st;
st.appendHead(5);
st.appendHead(2);
st.appendHead(3);
st.appendHead(9);
st.appendHead(3);
st.appendHead(2);
cout << st.deleteTail() << endl;
}