鏈隊列C++實現

鏈隊列時建立在單鏈表的基礎之上的。由於是動態分配節點內存,所以無需判滿。

          鏈隊列的形式如下:

1、隊列空

2、隊列存在數據

 

         下面介紹下C++實現的鏈隊列,VC6下調試通過。

1、文件組織

 

2、lq.h鏈隊列類的說明

  1. #ifndef _LQ_H_  
  2. #define _LQ_H_  
  3.   
  4. typedef int dataType;  
  5.   
  6. struct node                 //隊列節點  
  7. {  
  8.     dataType data;          //數據域  
  9.     node *next;             //指針域  
  10. };  
  11.   
  12. class lq  
  13. {  
  14. public:  
  15.     lq();                     //構造函數  
  16.     ~lq();                    //析構函數  
  17.     void push(dataType var);  //入隊  
  18.     void pop();               //出隊  
  19.     dataType front();         //取對頭元素,對頭不變化  
  20.     bool isEmpty();           //判空.head=tail=NULL時隊列爲空  
  21.   
  22. private:  
  23.     node *head;               //對頭指針  
  24.     node *tail;               //隊尾指針  
  25. };  
  26.   
  27. #endif  


3、lq.cpp鏈隊列的定義

  1. #include <iostream>  
  2. #include "lq.h"  
  3. using namespace std;  
  4.   
  5. lq::lq()  
  6. {  
  7.     head = NULL;           //head=tail=NULL時隊列爲空  
  8.     tail = NULL;  
  9. }  
  10.   
  11. lq::~lq()  
  12. {  
  13.     node *ptr = NULL;  
  14.   
  15.     while(head != NULL)  
  16.     {  
  17.         ptr = head->next;  
  18.         delete head;  
  19.         head = ptr;  
  20.     }  
  21. }  
  22.   
  23. void lq::push(dataType var)  
  24. {  
  25.     node *ptr = new node;  
  26.   
  27.     ptr->data = var;  
  28.     ptr->next = NULL;  
  29.     if(tail != NULL)           
  30.     {  
  31.         tail->next = ptr;       //不是入隊的第一個節點  
  32.     }  
  33.     else  
  34.     {  
  35.         head = ptr;             //如果是入隊的第一個節點  
  36.     }  
  37.     tail = ptr;  
  38. }  
  39.   
  40. void lq::pop()  
  41. {  
  42.     node *ptr = head->next;  
  43.   
  44.     delete head;  
  45.     head = ptr;  
  46.   
  47.     if(head == NULL)         //head時要將tail也賦爲NULL  
  48.     {  
  49.         tail = NULL;  
  50.     }  
  51. }  
  52.   
  53. dataType lq::front()  
  54. {  
  55.     return head->data;  
  56. }  
  57.   
  58. bool lq::isEmpty()  
  59. {  
  60.     return head == NULL && tail == NULL;  
  61. }  


4、main.cpp

  1. #include <iostream>  
  2. #include "lq.h"  
  3. using namespace std;  
  4.   
  5. int main()  
  6. {  
  7.     lq exp;  
  8.     int i =0;  
  9.   
  10.     for(i=0;i<100;i++)  
  11.     {  
  12.         exp.push(i);  
  13.     }  
  14.   
  15.     for(i=0;i<200;i++)  
  16.     {  
  17.         if(!exp.isEmpty())  
  18.         {  
  19.             cout<<exp.front()<<endl;  
  20.             exp.pop();  
  21.         }  
  22.     }  
  23.   
  24.     if(exp.isEmpty())  
  25.     {  
  26.         cout<<"隊列爲空!"<<endl;  
  27.     }  
  28.   
  29.     return 0;  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章