C++建立队列_利用链表

来源:互联网 发布:linux怎么进入grub界面 编辑:程序博客网 时间:2024/04/29 11:35

// c++ 实现链表队列

// .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;}//-------------------------------------------------




0 0
原创粉丝点击