鏈隊列時建立在單鏈表的基礎之上的。由於是動態分配節點內存,所以無需判滿。
鏈隊列的形式如下:
1、隊列空
2、隊列存在數據
下面介紹下C++實現的鏈隊列,VC6下調試通過。
1、文件組織
2、lq.h鏈隊列類的說明
- #ifndef _LQ_H_
- #define _LQ_H_
- typedef int dataType;
- struct node //隊列節點
- {
- dataType data; //數據域
- node *next; //指針域
- };
- class lq
- {
- public:
- lq(); //構造函數
- ~lq(); //析構函數
- void push(dataType var); //入隊
- void pop(); //出隊
- dataType front(); //取對頭元素,對頭不變化
- bool isEmpty(); //判空.head=tail=NULL時隊列爲空
- private:
- node *head; //對頭指針
- node *tail; //隊尾指針
- };
- #endif
3、lq.cpp鏈隊列的定義
- #include <iostream>
- #include "lq.h"
- using namespace std;
- lq::lq()
- {
- head = NULL; //head=tail=NULL時隊列爲空
- tail = NULL;
- }
- lq::~lq()
- {
- node *ptr = NULL;
- while(head != NULL)
- {
- ptr = head->next;
- delete head;
- head = ptr;
- }
- }
- void lq::push(dataType var)
- {
- node *ptr = new node;
- ptr->data = var;
- ptr->next = NULL;
- if(tail != NULL)
- {
- tail->next = ptr; //不是入隊的第一個節點
- }
- else
- {
- head = ptr; //如果是入隊的第一個節點
- }
- tail = ptr;
- }
- void lq::pop()
- {
- node *ptr = head->next;
- delete head;
- head = ptr;
- if(head == NULL) //head時要將tail也賦爲NULL
- {
- tail = NULL;
- }
- }
- dataType lq::front()
- {
- return head->data;
- }
- bool lq::isEmpty()
- {
- return head == NULL && tail == NULL;
- }
4、main.cpp
- #include <iostream>
- #include "lq.h"
- using namespace std;
- int main()
- {
- lq exp;
- int i =0;
- for(i=0;i<100;i++)
- {
- exp.push(i);
- }
- for(i=0;i<200;i++)
- {
- if(!exp.isEmpty())
- {
- cout<<exp.front()<<endl;
- exp.pop();
- }
- }
- if(exp.isEmpty())
- {
- cout<<"隊列爲空!"<<endl;
- }
- return 0;
- }