1.推斷隊列是否為空
2.在隊列尾部push進數據
3.從隊列頭部取出數據
4.刪除掉隊列首部的元素
我們這個Queue類須要什么成員變量?
答案是: (維護)隊列尾部結點、隊列大小就夠了。
我們來分析。尾部push數據的時候,我們僅僅須要在myback和myback->next之間插入這個結點。然后把這個myback指向這個結點就可以。取出和刪除頭部數據僅僅須要對myback->next進行操作就可以,復雜度是O(1),效率非常高。

剩下的一些實現細節看我以下的代碼實現:
//circle_list.h
#ifndef CIRCLE_LIST
#define CIRCLE_LIST
#include<iostream>
#include<string>
#include<cstring>
template <typename T>
class node//節點類
{
public:
T data;
node *next;
node(T da = 0, node *n = NULL) :data(da), next(n){}
};
template <typename T>
class Queue
{
public:
node<T> *myback;
int size;
Queue(node<T> *begin = NULL, int s = 0) :myback(begin),size(s){}
bool empty();
void enqueue(T value);//后面壓入
T front();
void display();
void dequeue();//前面刪除
~Queue();
Queue(const Queue<T> &temp);
Queue<T> operator=(const Queue<T>temp);
};
template <typename T>
bool Queue<T>::empty()
{
if (size == 0)
return true;
return false;
}
template <typename T>
Queue<T>::Queue(const Queue<T> &temp)
{
size = 0;
node<T>* scan = (temp.myback)->next;
while (scan != temp.myback)
{
enqueue(scan->data);
scan = scan->next;
}
enqueue(temp.myback->data);
}
template <typename T>
Queue<T> Queue<T>::operator=(const Queue<T> temp)
{
size = 0;
node<T>* scan = (temp.myback)->next;
while (scan != temp.myback)
{
enqueue(scan->data);
scan = scan->next;
}
enqueue(temp.myback->data);
return *this;
}
template <typename T>
void Queue<T>::enqueue(T value)
{
node<T>*last = new node<T>;
last->data = value;
if (size == 0)
{
myback = last;
myback->next = myback;
}
else
{
node<T> *temp = myback->next;
myback->next = last;
last->next = temp;
myback = last;
myback->next = temp;
}
size++;
}
template <typename T>
T Queue<T>::front()
{
return (myback->next)->data;
}
template <typename T>
void Queue<T>::display()
{
if (size == 1)
{
cout << myback->data << endl;
return;
}
else
{
node<T> *first = myback->next;
while (first != myback)
{
cout << first->data << " ";
first = first->next;
}
cout << myback->data;
cout << endl;
}
}
template <typename T>
void Queue<T>::dequeue()
{
node<T>*cur = myback->next;
node <T>*now = cur->next;
myback->next = now;
delete cur;
size--;
}
template <typename T>
Queue<T>::~Queue()
{
if (size == 0){}
else
{
node<T> *p = myback->next;
node<T> *nex = p->next;
while (p != myback)
{
delete p;
p = nex;
nex = nex->next;
}
delete myback;
}
}
#endif
進行測試:
//main.cpp
#include"circle_list.h"
using namespace std;
int main()
{
Queue<int> q;
cout <<"隊列是否為空?"<< q.empty() << endl;
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
cout << "輸出第一個隊列中的數據:" << endl;
q.display();
Queue<int> a(q);
cout << "輸出通過拷貝構造函數建立的隊列中的數據:" << endl;
a.display();
Queue<int> b;
b = q; cout << "輸出通過賦值運算符重載建立的隊列中的數據:" << endl;
b.display();
cout << "輸出隊列首的元素:" << endl;
cout << q.front() << endl;
q.dequeue();
cout << "刪除隊首元素后的隊列:" << endl;
q.display();
//cout << q.empty() << endl;
return 0;
}
實驗結果截圖;
