队列(Queue)是只允许在一端进行插入,而在另一端进行删除的运算受限的线性表
(1)允许删除的一端称为队头(Front)。
(2)允许插入的一端称为队尾(Rear)。
(3)当队列中没有元素时称为空队列。
(4)队列亦称作先进先出(First In First Out)的线性表,简称为FIFO表。
测试代码如下:
(1)允许删除的一端称为队头(Front)。
(2)允许插入的一端称为队尾(Rear)。
(3)当队列中没有元素时称为空队列。
(4)队列亦称作先进先出(First In First Out)的线性表,简称为FIFO表。
队列的修改是依先进先出的原则进行的。新来的成员总是加入队尾(即不允许"加塞"),每次离开的成员总是队列头上的(不允许中途离队),即当前"最老的"成员离队。
队列定义如下:
- #ifndef LINKEDQUEUE
- #define LINKEDQUEUE
- #include <iostream>
- using std::ostream;
- template <typename T>
- class LinkedQueue
- {
- private:
- struct Node
- {
- T data;//值域
- Node *next;//后继
- Node(Node *node = nullptr) : next(node)
- {
- }
- Node(const T &value,Node *node = nullptr) : data(value),next(node)
- {
- }
- };
- Node *front;//头
- Node *rear;//尾
- public:
- LinkedQueue() : front(nullptr),rear(nullptr)
- {
- }
- ~LinkedQueue()
- {
- makeEmpty();
- }
- void makeEmpty()//队列清空
- {
- Node *p ;
- while(front)
- {
- p = front;
- front = front->next;
- delete p;
- }
- }
- bool enQueue(const T &value)//进队
- {
- if(isEmpty())
- {
- front = rear = new Node(value);
- return front == nullptr ? true : false;
- }
- else
- {
- rear->next = new Node(value);
- rear = rear->next;
- return rear == nullptr ? true : false;
- }
- }
- bool deQueue(T &x)//出队
- {
- if(isEmpty())
- {
- return false;
- }
- else
- {
- Node *p = front;
- x = front->data;
- front = front->next;
- delete p;
- return true;
- }
- }
- bool isEmpty() const
- {
- return front == nullptr;
- }
- bool getFront(T &x)
- {
- if(isEmpty())
- {
- return false;
- }
- else
- {
- Node *p = front;
- x = front->data;
- return true;
- }
- }
- int size()
- {
- Node *p = front;
- int k = 0;
- while(p)
- {
- p = p->next;
- ++k;
- }
- return k;
- }
- friend ostream & operator<<(ostream &out,LinkedQueue<T> &lq)
- {
- Node *p = lq.front;
- for(int i = 1; i <= lq.size(); i++)
- {
- out << "#" << i <<":" << p->data << endl;
- p = p->next;
- }
- return out;
- }
- };
- #endif
测试代码如下:
- #include "linkedQueue.h"
- #include <fstream>
- using std::cin;
- using std::cout;
- using std::endl;
- using std ::ifstream;
- int main()
- {
- ifstream fin("data.txt");
- LinkedQueue<int> que;
- int data;
- while (!fin.eof()){
- fin >> data;
- que.enQueue(data);
- }
- cout << "The queue in the file is:\n" << que << endl;
- que.getFront(data);
- cout << "The front in the queue is: " << data << endl;
- cout << "Delete the front in turn, the result is:" << endl;
- int len = que.size();
- for(int i = 0; i < len; i++){
- que.deQueue(data);
- cout << "Delete " << data << ", then the queue is:\n";
- cout << que << endl;
- }
- system("pause");
- return 0;
- }