用两个栈实现队列的push() 和 pop()
#include <iostream>
#include <stack>
#include <stdexcept>
using namespace std;
template <class T>
class CQueue
{
public:
CQueue() {};
~CQueue() {};
void appendTail(const T& node);
T deleteHead();
private:
stack<T> stack1;
stack<T> stack2;
};
template <class T>
void CQueue<T>::appendTail(const T& node)
{
stack1.push(node);
}
template <class T>
T CQueue<T>::deleteHead()
{
if (stack2.empty())
{
while (!stack1.empty())
{
T& tmp = stack1.top();
stack1.pop();
stack2.push(tmp);
}
}
if (stack2.empty())
{
throw runtime_error(" queue is empty");
}
T head = stack2.top();
stack2.pop();
return head;
}
void Test(int actual, int excepted)
{
if (actual == excepted)
cout << "Test passed.\n";
else
cout << "Test failed.\n";
}
int main()
{
try {
CQueue<int> queue;
queue.appendTail(1);
queue.appendTail(2);
queue.appendTail(3);
int head = queue.deleteHead();
Test(head,1);
head = queue.deleteHead();
Test(head,2);
queue.appendTail(4);
head = queue.deleteHead();
Test(head,3);
queue.appendTail(5);
head = queue.deleteHead();
Test(head,4);
head = queue.deleteHead();
Test(head,5);
}
catch (runtime_error err) {
cout << err.what() << endl;
}
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-29 19:06:10