基本数据结构:链式队列
2013-12-23 22:08
169 查看
队列(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; }
相关文章推荐
- 【数据结构】链式队列的基本操作
- 【数据结构与算法】基本数据结构——队列的链式表示
- 基本数据结构:链式队列
- 第九篇:基本数据结构——队列的链式表示
- 数据结构-链式队列的基本操作
- PHP数据结构之七_队列的链式存储和队列的基本操作
- 基本数据结构,循环队列的顺序实现。
- 队列的链式表示和实现(数据结构)
- 【数据结构】 链式队列的一些操作
- 数据结构 - 栈和队列的基本运算实现
- 【数据结构与算法】基本数据结构——线性表的链式表示
- 链式队列基本操作之code_legend
- 【郝斌数据结构自学笔记】35-46_队列的定义、分类_链式队列伪算法的讲解_循环队列伪算法的讲解
- 数据结构--顺序队列基本操作
- 数据结构_线性表_链式存储_单链表 的基本操作
- [数据结构]程杰队列的链式存储结构及实现代码
- 基本数据结构(栈和队列)
- 数据结构-链队列的基本操作
- 算法导论 第三部分——基本数据结构——栈、队列、链表、散列表
- 队列---链式队列【数据结构】