主要思想
有兩個棧
stack1
和stack2
芽偏,
在push時雷逆,直接壓入stack1
在pop時,判斷stack2是否為空污尉,空則將stack1的數(shù)據(jù)壓入stack2膀哲,不空則只需將stack2的棧頂彈出往产。
代碼實現(xiàn)
#ifndef _MYQUEUE_H_
#define _MYQUEUE_H_
#include<iostream>
#include<stack>
using namespace std;
template<class T> class Test
{
public:
Test();
T pop();
void push(T element);
private:
stack<T> stk1;
stack<T> stk2;
};
template<class T> Test<T>::Test() { }
template<class T> T Test<T>::pop()
{
//TODO:檢查stk2中是否為空,不空某宪,則直接彈出stk2的棧頂;
//否則仿村,將stk1中的size-1個倒入stk2;返回stk1 棧底元素
T retVal;
if (!stk2.empty())
{
retVal = stk2.top();
stk2.pop();
return retVal;
}
else
{
T tmp;
while (stk1.size() > 1)
{
tmp = stk1.top();
stk2.push(tmp);
stk1.pop();
}
tmp = stk1.top();
stk1.pop();
retVal = tmp;
return retVal;
}
}
template<class T> void Test<T>::push(T element)
{
stk1.push(element);
}
#endif
注意,模板類的聲明和定義需要在一個文件中