队列
2016-01-02 13:57
302 查看
#pragma once #include<iostream> #include<assert.h> using namespace std; template<class T> struct Node { Node(const T& x) :_data(x) , _next(NULL) {} T _data; Node<T>* _next; }; template<class T> class Queue { //先进先出 public: Queue() :_head(NULL) , _tail(NULL) {} void Push(const T&x) { if (_head == NULL) { _head = new Node<T>(x); _tail = _head; } else { _tail->_next = new Node<T>(x); _tail = _tail->_next; } } void Pop() { if (_head == _tail) { delete _head; _head = _tail = NULL; } else { Node<T>*del = _head; _head = _head->_next; delete del; } } bool IsEmpty() { return _head == NULL; } const T& Front() { assert(_head);//需判断 return _head->_data; } const T& Back() { assert(_tail); return _tail->_data; } protected: Node<T>* _head; Node<T>* _tail; }; void TestQueue() { Queue<int> q1; q1.Push(1); q1.Push(2); q1.Push(3); q1.Push(4); q1.Push(5); q1.Push(6); while (!q1.IsEmpty()) { cout << q1.Front() << " "; q1.Pop(); } cout << endl; } void TestQueue1() { Queue<string> q2; q2.Push("ab"); q2.Push("cd"); q2.Push("ef"); q2.Push("gh"); q2.Push("lm"); q2.Push("kl"); while (!q2.IsEmpty()) { cout << q2.Front() << " "; q2.Pop(); } cout << endl; } #include<iostream> using namespace std; #include"Queue.h" int main() { //栈的特点:后进先出,只能从尾部进行操作 //TestStack1(); TestQueue1(); system("pause"); return 0; }
相关文章推荐
- C#线程队列用法实例分析
- 算法系列15天速成 第九天 队列
- C语言单链队列的表示与实现实例详解
- mysql 队列 实现并发读
- C#队列Queue用法实例分析
- C#多线程处理多个队列数据的方法
- C语言循环队列的表示与实现实例详解
- C++循环队列实现模型
- C#内置队列类Queue用法实例
- Array栈方法和队列方法的特点说明
- C#通过链表实现队列的方法
- C#队列Queue多线程用法实例
- C#数据结构与算法揭秘五 栈和队列
- C++中队列的建立与操作详细解析
- PHP实现的memcache环形队列类实例
- php基于双向循环队列实现历史记录的前进后退等功能
- 队列在编程中的实际应用(php)
- Go语言的队列和堆栈实现方法
- C++队列用法实例
- PHP队列用法实例