1、两个栈实现一个队列,思路如下:
代码如下:
#include<iostream>
#include<stack>
#include<queue>
using namespace std;
template <typename T>
class CQueue
{
public:
CQueue(void){}
~CQueue(void){}
void appendTail(const T& node);
T deleteHead();
private:
stack<T> stack1;
stack<T> stack2;
};
template<typename T>
void CQueue<T>:: appendTail(const T&node)//插入
{
stack1.push(node);
}
template <typename T>
T CQueue<T>::deleteHead()//删除
{
while(! stack1.empty ())
{
T tmp = stack1.top();
stack1.pop();
stack2.push(tmp);
}
if(!stack2.empty())
{
T top = stack2.top();
stack2.pop();
return top;
}else
{
exit(0);
}
}
int main()
{
CQueue<int> c1;
int arr[] = {1,2,3,4,5,6,7,8,9};
int len = sizeof(arr)/sizeof(arr[0]);
for(int i=0;i<len;++i)
{
c1.appendTail(arr[i]);
}
for(int i=0;i<len;++i)
{
cout<<c1.deleteHead()<<" ";
}
return 0;
}
2、两个队列实现一个栈,思路如下:
代码如下:
#include<iostream>
#include<stack>
#include<queue>
using namespace std;
template <typename T>
class CStack
{
public:
CStack(void){}
~CStack(void){}
void appendTail(const T& node);
T deleteHead();
private:
queue<T> queue1;
queue<T> queue2;
};
template<typename T>
void CStack<T>:: appendTail(const T&node)//插入
{
queue1.push(node);
}
template <typename T>
T CStack<T>::deleteHead()//删除
{
T pop;
if(!queue1.empty())
{
while(queue1.size() > 1)
{
T tmp = queue1.front();
queue1.pop();
queue2.push(tmp);
}
pop = queue1.front();
queue1.pop();
}else
{
while(queue2.size() > 1)
{
T tmp = queue2.front();
queue2.pop();
queue1.push(tmp);
}
pop = queue2.front();
queue2.pop();
}
return pop;
}
int main()
{
CStack<int> c1;
int arr[] = {1,2,3,4,5,6,7,8,9};
int len = sizeof(arr)/sizeof(arr[0]);
for(int i=0;i<len;++i)
{
c1.appendTail(arr[i]);
}
for(int i=0;i<5;++i)//5
{
cout<<c1.deleteHead()<<" ";
}
int brr[] = {100,101,102,103};
int lenbrr = sizeof(brr)/sizeof(arr[0]);
for(int i=0;i<lenbrr;++i)
{
c1.appendTail(brr[i]);
}
for(int i=0;i<len-5+lenbrr;++i)
{
cout<<c1.deleteHead()<<" ";
}
return 0;
}