寫在前面:上一篇博客已經完成使用c++實現隊列的鏈式存儲結構,參見鏈接:c++ 實現隊列的順序存儲結構
自己認爲無論是線性表、棧還是隊列等等結構,鏈式結構總是要比順序結構難一點,因爲順序存儲結構就是玩數組嘛,數組大家都能玩的轉;
但鏈式結構肯定是指針操作,而有了指針,程序必將變得複雜,所以實現起來可能稍微有點困難,但是換句話說,鏈式不就是玩指針嘛,相信大家指針也一定都能玩的轉.
話不多說,進入正題:
一、首先還是要搞清楚三個問題:
1、實現隊列的鏈式存儲結構就是實現簡單的鏈表:只允許在尾部插入元素,只允許在頭部刪除元素,這裏分別叫入隊和出隊,
2、明白兩個指針:front和rear。
front:隊頭指針,rear:隊尾指針;
3、三個等式:
(1)隊列爲空的條件依然是:
front == rear;
(2)因爲是鏈式存儲,就不存在隊滿的現象:
二、實現過程(保證可復現):
1、首先是頭文件定義(類定義)部分:
#pragma once
#include <iostream>
#include <string>
using namespace std;
template <class ElemType>
struct QueueNode {
ElemType data;
QueueNode *next;
};
template <class ElemType>
class LinkQueue {
public:
LinkQueue();
~LinkQueue();
void enQueue(const ElemType &e);
void deQueue();
bool isEmpty();
void showQueue();
int getSize();
private:
QueueNode<ElemType> *front;
QueueNode<ElemType> *rear;
int size;
};
2、其次是函數定義部分:
#include "linkQueue.h"
template<class ElemType>
inline LinkQueue<ElemType>::LinkQueue(){
this->front = new QueueNode<ElemType>;
if (!front) return;
this->rear = this->front;
this->size = 0;
}
template<class ElemType>
inline LinkQueue<ElemType>::~LinkQueue(){
delete this->front;
}
template<class ElemType>
void LinkQueue<ElemType>::enQueue(const ElemType & e){
QueueNode<ElemType> *s = new QueueNode<ElemType>;
s->data = e;
s->next = nullptr;
this->rear->next = s;
this->rear = s;
this->size++;
}
template<class ElemType>
void LinkQueue<ElemType>::deQueue(){
if (isEmpty()) {
cout << "隊列爲空隊列!" << endl;
return;
}
QueueNode<ElemType> *ptr = this->front->next;
ElemType e;
e = ptr->data;
this->front->next = ptr->next;
if (rear == ptr) {
this->rear = this->front;
}
this->size--;
delete ptr;
}
template<class ElemType>
bool LinkQueue<ElemType>::isEmpty(){
if (front == rear)
return true;
return false;
}
template<class ElemType>
void LinkQueue<ElemType>::showQueue(){
QueueNode<ElemType> *ptr = front->next;
if (isEmpty()) {
cout << "隊列爲空隊列" << endl;
return;
}
while (ptr) {
cout << ptr->data << " ";
ptr = ptr->next;
}
}
template<class ElemType>
int LinkQueue<ElemType>::getSize(){
return this->size;
}
3、最後是函數測試部分(main):
#include <iostream>
#include "linkQueue.cpp"
using namespace std;
int main()
{
LinkQueue<int> lq;
cout << "************************" << endl;
cout << "實例化的空隊列:" << endl;
cout << "隊列的長度爲:" << lq.getSize() << endl;
cout << "************************" << endl;
cout << "執行入隊操作後:" << endl;
for (int i = 0; i < 10; ++i) {
lq.enQueue(i);
}
cout << "隊列的長度爲:" << lq.getSize() << endl;
lq.showQueue();
cout << "************************" << endl;
cout << "執行出隊操作後:" << endl;
lq.deQueue();
cout << endl;
cout << "隊列的長度爲:" << lq.getSize() << endl;
lq.showQueue();
cout << endl;
system("pause");
return 0;
}
4、實現結果:
![在這裏插入圖片描述]()