队
2016-04-11 23:00
267 查看
队
队即是仅允许在尾部进入,在头部出的顺序表,即“先进先出”
队即是仅允许在尾部进入,在头部出的顺序表,即“先进先出”
#include<iostream> #include<assert.h> using namespace std; template<class T> struct Node { T _data; Node<T>*_next; Node(const T &x) :_data(x) , _next(NULL) { } }; template<class T> class Queue { public: Queue() :_head(NULL) , _tail(NULL) {} Queue(const Queue<T>&q) :_head(NULL) , _tail(NULL) { Node<T>*cur = q._head; while (cur) { Push(cur->_data); cur = cur->_next; } } Queue& operator=( Queue<T>&q) { swap(_head, q._head); swap(_tail, q._tail); return *this; } ~Queue() { if (_head == NULL) return; Node<T>*cur = _head; while (cur->_next!=NULL) { Node<T>*del=cur; cur = cur->_next; delete del; } delete cur; _head = NULL; _tail = NULL; } public: bool Empty() { return _head==NULL; } void Push(const T&x)//尾插 { Node<T>*newNode = new Node<T>(x); if (_head == NULL) { _head = newNode; _tail = newNode; } else { _tail->_next = newNode; _tail = newNode; } } void Pop()//头删 { assert(_head); if (_head == _tail) { delete _head; _head = _tail = NULL; } else { Node<T>*del = _head; _head = _head->_next; delete del; } } T& Front()//队首 { assert(_head); return _head->_data; } T& Back()//队尾 { assert(_tail) return _tail->_data; } private: Node<T>* _head; Node<T>* _tail; }; void test() { Queue<int> q1; q1.Push(1); q1.Push(2); q1.Push(3); q1.Push(4); q1.Push(5); q1.Push(6); q1.Push(7); q1.Push(8); Queue<int> q2; q2 = q1; Queue<int>q3(q2); while (!q3.Empty()) { cout << q3.Front() << " "; q3.Pop(); } } int main() { test(); getchar(); return 0; }
相关文章推荐
- C#数据结构之顺序表(SeqList)实例详解
- Lua教程(七):数据结构详解
- 解析从源码分析常见的基于Array的数据结构动态扩容机制的详解
- C#数据结构之队列(Quene)实例详解
- C#数据结构揭秘一
- C#数据结构之单链表(LinkList)实例详解
- 数据结构之Treap详解
- 用C语言举例讲解数据结构中的算法复杂度结与顺序表
- C#数据结构之堆栈(Stack)实例详解
- C#数据结构之双向链表(DbLinkList)实例详解
- JavaScript数据结构和算法之图和图算法
- Java数据结构及算法实例:冒泡排序 Bubble Sort
- Java数据结构及算法实例:插入排序 Insertion Sort
- Java数据结构及算法实例:考拉兹猜想 Collatz Conjecture
- java数据结构之java实现栈
- java数据结构之实现双向链表的示例
- Java数据结构及算法实例:选择排序 Selection Sort
- Java数据结构及算法实例:朴素字符匹配 Brute Force
- Java数据结构及算法实例:汉诺塔问题 Hanoi
- Java数据结构及算法实例:快速计算二进制数中1的个数(Fast Bit Counting)