C++建立队列_利用链表
生活随笔
收集整理的這篇文章主要介紹了
C++建立队列_利用链表
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
// 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; } //-------------------------------------------------
總結
以上是生活随笔為你收集整理的C++建立队列_利用链表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode双指针(python与c
- 下一篇: C++二级指针