C++建立队列_利用链表
2014-03-23 18:57
381 查看
// c++ 实现链表队列
// .h 文件
// 文件名: Queue.h
// .cpp 文件
// 文件名Queue.cpp
// 主函数
// 文件名:main.cpp
// .h 文件
// 文件名: Queue.h
//------------------------------------------------- #pragma once //------------------------------------------------- #include <iostream> using namespace std; //------------------------------------------------- typedef int dataType; //------------------------ // 节点类 // 结构名称 Node // 参数说明data 为关键字 // next 为指向下一个节点的指针 struct Node { dataType data; Node * next; }; //------------------------------------------------- // 队列类, // 类名 Queue , 建立链表队列 class Queue { public: Queue(void); ~Queue(void); void push(dataType ); void pop(); dataType front(); // 获取头元素 bool IsEmpty(); // private: Node * head ; // 头指针 Node * tail; // 尾指针 }; //-------------------------------------------------
// .cpp 文件
// 文件名Queue.cpp
//------------------------------------------------- #include "Queue.h" //------------------------------------------------- Queue::Queue(void) { head = NULL; tail = NULL; // the queue is empty when head ==NULL tail == NULL } //------------------------------------------------- Queue::~Queue(void) { Node * ptr = NULL; while (head != NULL ) { ptr = head; head = head->next; delete ptr ; } } //------------------------------------------------- void Queue::push(dataType value ) { Node * ptr = new Node ; ptr->data = value; ptr->next = NULL; if (tail != NULL ) { tail->next = ptr; }else { head = ptr ; } tail = ptr ; } //------------------------------------------------- void Queue::pop() { Node *ptr = head ; head = head->next; delete ptr ; ptr = NULL; if (head == NULL ) tail = NULL ; } //------------------------------------------------- dataType Queue::front() // 获取头元素 ,当队列为空时,返回值为0 { if (this->IsEmpty() == true ) { cout << "the Queue is empty!!" ; return 0; } return head->data; } //------------------------------------------------- bool Queue::IsEmpty() { return head==NULL && tail == NULL; } //-------------------------------------------------
// 主函数
// 文件名:main.cpp
//------------------------------------------------- // 2014--03--23 // C++ 实现链表队列 //------------------------------------------------- #include "Queue.h" //------------------------------------------------- // 编写主函数进行测试 int main() { Queue qu; qu.push(324); qu.push(3224); qu.push(32324); qu.push(3214); qu.push(322354); cout << qu.front() << endl; qu.pop();cout << qu.front() << endl; qu.pop();cout << qu.front() << endl; qu.pop();cout << qu.front() << endl; qu.pop();cout << qu.front() << endl; qu.pop();cout << qu.front() << endl; cout << qu.IsEmpty() << endl; return 0; } //-------------------------------------------------