队列(链表实现)
2010-12-31 11:17
253 查看
#ifndef QUEUE_H #define QUEUE_H #include<iostream> template<typename T> struct Node { T data; struct Node *next; }; template<typename T> class Queue { Node<T> *head; Node<T> *tail; int length; public: Queue(); ~Queue(); bool IsFull()const; int enqueue(T elem); int dequeue(); bool IsEmpty()const; int getLength()const; T getHead()const; T getTail()const; }; template<typename T> Queue<T>::Queue() { head=new Node<T>; head->data=0; head->next=NULL; tail=head; length=0; } template<typename T> Queue<T>::~Queue() { delete head; } template<typename T> bool Queue<T>::IsFull()const { try { Node<T> *tmp=new Node<T>; delete tmp; return false; } catch(std::bad_alloc exceptin) { return true; } } template<typename T> int Queue<T>::enqueue(T elem) { if(length==0) { head->data=elem; head->next=NULL; tail=head; } else { if(!IsFull()) { Node<T> *tmp=new Node<T>; tmp->data=elem; tmp->next=NULL; tail->next=tmp; tail=tail->next; } } ++length; return 0; } template<typename T> bool Queue<T>::IsEmpty()const { if(length==0&&head==tail)return true; else return false; } template<typename T> int Queue<T>::dequeue() { if(IsEmpty())return -1; else if(length==1) { head->data=0; --length; return 0; } else { if(!IsFull()) { Node<T> *tmp=head; head=head->next; delete tmp; --length; return 0; } } } template<typename T> int Queue<T>::getLength()const { return length; } template<typename T> T Queue<T>::getHead()const { return head->data; } template<typename T> T Queue<T>::getTail()const { return tail->data; } #endif
// queue.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "queue.h" using namespace std; int _tmain(int argc, _TCHAR* argv[]) { Queue<int> A; int i=9; while(i!=0) { A.enqueue(i); --i; } cout<<A.getLength()<<" "<<A.getHead()<<" "<<A.getTail()<<"/n"; A.dequeue(); cout<<A.getLength()<<" "<<A.getHead()<<" "<<A.getTail()<<"/n"; system("pause"); return 0; }
相关文章推荐
- 数据结构---队列链表c实现
- 队列的链表实现
- 队列实现 (双向循环链表 C++)
- 一种高效双端队列(链表)实现方式
- 数据结构---双向链表实现队列与循环链表
- 单链表队列的简单实现
- 队列的链式存储---链表实现(有头结点)
- 用链表实现的无锁栈和无锁队列存在的ABA问题
- 线性表 及Java实现 顺序表、链表、栈、队列
- C++学习笔记(四)指针实现的链表、堆栈、队列、二叉查找树
- 算法导论第十章 基本数据结构实现(栈,队列,链表),课后题答案
- C++中采用链表实现队列
- 20140506 visio 画布大小 栈实现队列 堆空闲内存地址链表 堆最大可分配的内存 可用内存链表
- 数据结构与算法 ---- 线性表 及Java实现 顺序表、链表、栈、队列
- 算法导论第三版第十章 单链表实现栈和队列(思路简单清晰)
- C++模板链表实现优先级队列
- C++用模板实现双链表和队列
- java 实现数组队列和链表队列
- 基于链表的队列实现
- 数据结构_链表实现无限循环的"环"结构/循环队列