版权声明:您好,转载请留下本人博客的地址,谢谢 https://blog.csdn.net/hongbochen1223/article/details/48655805
队列的链表实现代码(在这做一下记录):
//============================================================================
// Name : LinkedQueue.cpp
// Author : 陈洪波
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include "Exception.h"
#include <iostream>
using namespace std;
template<class T>
class Node;
template<class T>
class LinkedQueue {
public:
LinkedQueue() {
front = rear = 0;
}
~LinkedQueue();
bool IsEmpty() const {
return ((front) ? false : true);
}
bool IsFull() const;
T First() const;
T Last() const;
LinkedQueue<T>& Add(const T& x);
LinkedQueue<T>& Delete(T& x);
void Output(ostream& out) const;
int Size() const;
private:
Node<T>* front;
Node<T>* rear;
};
template<class T>
class Node {
friend class LinkedQueue<T> ;
private:
T data;
Node<T> *link;
};
template<class T>
LinkedQueue<T>::~LinkedQueue() {
Node<T> *next;
while (front) {
next = front->link;
delete front;
front = next;
}
}
template<class T>
bool LinkedQueue<T>::IsFull() const {
Node<T> *p;
try {
p = new Node<T>;
delete p;
return false;
} catch (NoMem) {
return true;
}
}
template<class T>
T LinkedQueue<T>::First() const {
if (IsEmpty())
throw OutOfBounds();
return front->data;
}
template<class T>
T LinkedQueue<T>::Last() const {
if (IsEmpty())
throw OutOfBounds();
return rear->data;
}
template<class T>
LinkedQueue<T>& LinkedQueue<T>::Add(const T& x) {
if (IsFull())
throw NoMem();
Node<T> *next = new Node<T>;
next->data = x;
next->link = 0;
if (front){
rear->link = next;
rear = next;
}else {
front = next;
rear = next;
}
return *this;
}
template<class T>
LinkedQueue<T>& LinkedQueue<T>::Delete(T& x) {
if (IsEmpty())
throw OutOfBounds();
x = front->data;
Node<T>* p = front;
front = front->link;
delete p;
return *this;
}
template<class T>
void LinkedQueue<T>::Output(ostream& out) const {
Node<T>* p = front;
while (p) {
cout << p->data << " ";
p = p->link;
}
cout << endl;
}
template<class T>
ostream& operator<<(ostream& out, const LinkedQueue<T>& x) {
x.Output(out);
return out;
}
template<class T>
int LinkedQueue<T>::Size() const{
int count = 0;
if(IsEmpty())
return 0;
Node<T>* p = front;
while(p){
count++;
p = p->link;
}
return count;
}
int main() {
LinkedQueue<int> lq;
lq.Add(1);
lq.Add(2);
lq.Add(3);
lq.Add(4);
lq.Add(5);
cout << lq << endl;
return 0;
}