您的位置:首页 > 其它

队列(链表实现)

2010-12-31 11:17 253 查看
#ifndef QUEUE_H
#define QUEUE_H
#include<iostream>
template<typename T>
struct Node
{
T data;
struct Node *next;
};
template<typename T>
class Queue
{
Node<T> *head;
Node<T> *tail;
int length;
public:
Queue();
~Queue();
bool IsFull()const;
int enqueue(T elem);
int dequeue();
bool IsEmpty()const;
int getLength()const;
T getHead()const;
T getTail()const;
};
template<typename T>
Queue<T>::Queue()
{
head=new Node<T>;
head->data=0;
head->next=NULL;
tail=head;
length=0;
}
template<typename T>
Queue<T>::~Queue()
{
delete head;
}
template<typename T>
bool Queue<T>::IsFull()const
{
try
{
Node<T> *tmp=new Node<T>;
delete tmp;
return false;
}
catch(std::bad_alloc exceptin)
{
return true;
}
}
template<typename T>
int Queue<T>::enqueue(T elem)
{
if(length==0)
{
head->data=elem;
head->next=NULL;
tail=head;
}
else
{
if(!IsFull())
{
Node<T> *tmp=new Node<T>;
tmp->data=elem;
tmp->next=NULL;
tail->next=tmp;
tail=tail->next;
}
}
++length;
return 0;
}
template<typename T>
bool Queue<T>::IsEmpty()const
{
if(length==0&&head==tail)return true;
else return false;
}
template<typename T>
int Queue<T>::dequeue()
{
if(IsEmpty())return -1;
else if(length==1)
{
head->data=0;
--length;
return 0;
}
else
{
if(!IsFull())
{
Node<T> *tmp=head;
head=head->next;
delete tmp;
--length;
return 0;
}
}
}
template<typename T>
int Queue<T>::getLength()const
{
return length;
}
template<typename T>
T Queue<T>::getHead()const
{
return head->data;
}
template<typename T>
T Queue<T>::getTail()const
{
return tail->data;
}
#endif


// queue.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "queue.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
Queue<int> A;
int i=9;
while(i!=0)
{
A.enqueue(i);
--i;
}
cout<<A.getLength()<<" "<<A.getHead()<<" "<<A.getTail()<<"/n";
A.dequeue();
cout<<A.getLength()<<" "<<A.getHead()<<" "<<A.getTail()<<"/n";
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: