您的位置:首页 > 其它

简单队列的实现(基于链表)

2014-03-04 17:04 417 查看
实现一个简单的队列,基于链表。

#ifndef _LINKEDQUEUE_
#define _LINKEDQUEUE_

#include <iostream>
#include <stdexcept>
using namespace std;

template <typename T>
class LinkedQueue
{
public:
LinkedQueue() : _size(0),_head(NULL),_tail(NULL) {}
~LinkedQueue() { Clear(); }
LinkedQueue(const LinkedQueue& rhs) : _size(0),_head(NULL),_tail(NULL)
{
operator=(rhs);
}

const LinkedQueue& operator= (const LinkedQueue& rhs)
{
if( this != &rhs )
{
Clear();
LinkedQueueNode* temp = rhs._head;
while( temp != NULL)
{
this->Enqueue(temp->data);
temp = temp->next;
}
}

return *this;
}

int Size() const { return _size; }
bool IsEmpty() const { return _size == 0; }
void Clear()
{
_size = 0;

LinkedQueueNode* temp = _head;
while(temp != NULL)
{
_head = _head->next;
delete temp;
temp = _head;
}

_head = NULL;
_tail = NULL;
}

void Print() const
{
cout<< "Size=" << _size <<endl;
LinkedQueueNode* temp = _head;
while(temp != NULL)
{
cout << temp->data << ",";
temp = temp->next;
}
cout << endl;
}

void Enqueue(const T& value)
{
if(_size == 0)
{
_tail = new LinkedQueueNode(value,NULL);
_head = _tail;
}
else
{
_tail->next = new LinkedQueueNode(value,NULL);
_tail = _tail->next;
}

++_size;
}

T Dequeue()
{
if(IsEmpty())
throw logic_error("Queue is empty");

LinkedQueueNode* temp = _head;
T value = temp->data;

if(_size == 1)
{
_head = _tail = NULL;
}
else
{
_head = _head->next;
}

--_size;
delete temp;
return value;
}

T& Peek() const
{
if(IsEmpty())
throw logic_error("Queue is empty");

return _head->data;
}

private:
class LinkedQueueNode
{
public:
T data;
LinkedQueueNode* next;
LinkedQueueNode(const T& v, LinkedQueueNode* n=NULL) : data(v),next(n) {}
};

private:
int _size;
LinkedQueueNode* _head;
LinkedQueueNode* _tail;
};
#endif


测试代码:

#include "LinkedQueue.cpp"

void LinkedQueueTest1();
void Test( void (*fp)() );

int main(int argc, char** argv)
{
Test(LinkedQueueTest1);
return 0;
}

void LinkedQueueTest1()
{
LinkedQueue<int> q;
q.Print();

q.Enqueue(1);
q.Enqueue(2);
q.Enqueue(3);
q.Enqueue(4);
q.Enqueue(5);
q.Print();

cout << "Peek=" << q.Peek() << endl;
cout << "Dequeue=" << q.Dequeue() << endl;
q.Print();

q.Enqueue(6);
q.Print();

q.Dequeue();
q.Dequeue();
q.Print();

LinkedQueue<int> q1 = q;
cout<< "q1 content" << endl;
q1.Print();

cout << q1.Dequeue() << endl;
cout << q1.Dequeue() << endl;
cout << q1.Dequeue() << endl;
q1.Print();

cout << "q content" << endl;
q.Print();
}

void Test( void (*fp)() )
{
try
{
fp();
}
catch(out_of_range e)
{
cout<< "Catch Exception:" << e.what() << endl;
}
catch(overflow_error e)
{
cout<< "Catch Exception:" << e.what() << endl;
}
catch(logic_error e)
{
cout<< "Catch Exception:" << e.what() << endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: