用两个栈实现一个队列,实现函数 appendTail deleteHead
QueueWithTwoStacks.cpp 文件: 定义控制台应用程序的入口点。
#include <stdlib.h>
#include "Queue.h"
//模板添加
void Test(char actual)
{
printf("test %c\n", actual);
}
int _tmain(int argc, _TCHAR* argv[])
{
CQueue<char> queue;
queue.appendTail('a');
queue.appendTail('b');
queue.appendTail('c');
char head = queue.deleteHead();
Test(head);
head = queue.deleteHead();
Test(head);
queue.appendTail('d');
head = queue.deleteHead();
Test(head);
queue.appendTail('e');
head = queue.deleteHead();
Test(head);
head = queue.deleteHead();
Test(head);
system("pause");
return 0;
}
Queue.h文件
#pragma once
#include <stack>
#include <exception>
using namespace std;
template<typename T> class CQueue
{
public:
CQueue();
~CQueue();
void appendTail(const T&node);
T deleteHead();
private:
stack<T> stack1;
stack<T> stack2;
};
template<typename T> CQueue<T>::CQueue()
{
}
template<typename T> CQueue<T>::~CQueue()
{
}
template<typename T> void CQueue<T>::appendTail(const T& element)
{
stack1.push(element);
}
template<typename T> T CQueue<T>::deleteHead()
{
//2 为空的时候
if (stack2.size() <= 0)
{
while(stack1.size() > 0)
{
T& data = stack1.top();
stack1.pop();
//把data放到statck2中
stack2.push(data);
}
}
if (stack2.size() == 0)
{
throw new exception("queue is empty");
}
//弹出2中的第一个
T head = stack2.top();
stack2.pop();
return head;
}
Queue.cpp文件
#include "Queue.h"
#include <queue>