#include <iostream>
#include<queue>
using namespace std;
template<typename T> class MyQueue
{
public:
MyQueue(void);
~MyQueue(void);
void appendTail(const T& node);
T deleteHead();
void Print();
private:
queue<T> queue1;
queue<T> queue2;
};
template<typename T>
MyQueue<T>::MyQueue(void)
{
}
template<typename T>
MyQueue<T>::~MyQueue(void)
{
}
template<typename T>
void MyQueue<T>::appendTail(const T& node)
{
//数据的插入原则:保持一个队列为空,一个队列不为空,往不为空的队列中插入元素
if (!queue1.empty())
{
queue1.push(node);
}
else
{
queue2.push(node);
}
}
template<typename T>
T MyQueue<T>::deleteHead()
{
T result = 0;
if (!queue1.empty())
{
while (queue1.size() > 1)
{
T& data = queue1.front();
queue1.pop();
queue2.push(data);
}
if (queue1.empty())
{
throw new exception("queue is empty");
}
result = queue1.front();
queue1.pop();
}
else
{
while (queue2.size() > 1)
{
T& data = queue2.front();
queue2.pop();
queue1.push(data);
}
if (queue2.empty())
{
throw new exception("queue is empty");
}
result = queue2.front();
queue2.pop();
}
return result;
}
template<typename T>
void MyQueue<T>::Print()
{
if (!queue1.empty())
{
int len = queue1.size();
for (int i = 0; i < len; ++i)
{
cout << queue1.front() << " ";
queue1.push(queue1.front());
queue1.pop();
}
}
else if (!queue2.empty())
{
int len = queue2.size();
for (int i = 0; i < len; ++i)
{
cout << queue2.front() << " ";
queue2.push(queue2.front());
queue2.pop();
}
}
}
int main()
{
MyQueue<int> queue;
cout << "往栈中添加元素:1 2 3" << endl;
queue.appendTail(1);
queue.appendTail(2);
queue.appendTail(3);
cout << "添加后栈内元素:";
queue.Print();
cout << endl << endl;
int data = queue.deleteHead();
cout << "删除的栈尾元素:" << data << endl;
cout << "删除后的栈元素:";
queue.Print();
cout << endl << endl;
cout << "往栈中添加元素:10 12" << endl;
queue.appendTail(10);
queue.appendTail(12);
cout << "添加后:";
queue.Print();
cout << endl << endl;
int data1 = queue.deleteHead();
cout << "删除的栈尾元素:" << data1 << endl;
cout << "删除后的栈元素:";
queue.Print();
cout << endl << endl;
return 0;
}
传送门:用两个栈实现一个栈