1 队列的定义
队列是只允许在一端(队尾)进行插入操作,而在另一端(队头)进行删除操作的线性表。
2 队列的特点
1)先进先出是队列最大的特点,是应用中非常常见的模型,例如排队;
2)队列也属于线性表,线性表的特性队列都拥有。
3 循环队列的实现及关键点
3.1 关键点
1)队列为空的条件:队头指针等于队尾指针,即head == tial;
2)队列中保留一个元素空间,当队列满时,尾指针和头指针之间还剩一个元素空间。队列为满的条件:(tial + 1) % quenceSize == head;
3)队列中元素个数为:(tial + quenceSize - head) % quenceSize。
3.2 实现
1 #ifndef CYCLESQUENCE_H 2 #define CYCLESQUENCE_H 3 4 typedef int ElemType; 5 6 class CycleQuence { 7 private: 8 ElemType* m_pData; //数组地址 9 int m_nHead; //首元素位置 10 int m_nTial; //尾元素位置 11 int m_nMaxSize; //数组长度 12 13 public: 14 CycleQuence(int maxSize); 15 ~CycleQuence(); 16 void ClearQuence() { m_nHead = 0, m_nTial = 0; } //清空队列 17 bool EnterQuence(ElemType elem); //入队 18 bool DeleteQuence(ElemType* pElem); //出队 19 void VisitQuence() const; //查看队列元素 20 bool IsEmpty() const { return m_nHead == m_nTial; } //判断是否为空 21 bool IsFull() const { return m_nHead == (m_nTial + 1) % m_nMaxSize; } //判断是否为满 22 }; 23 24 #endif
1 #include "pch.h" 2 #include "CycleSquence.h" 3 #include <iostream> 4 5 CycleQuence::CycleQuence(int maxSize) 6 { 7 m_nHead = 0; 8 m_nTial = 0; 9 m_nMaxSize = maxSize; 10 m_pData = new ElemType[maxSize]; 11 } 12 13 CycleQuence::~CycleQuence() 14 { 15 delete[] m_pData; 16 } 17 18 bool CycleQuence::EnterQuence(ElemType elem) //入队 19 { 20 if (IsFull()) //队满 21 { 22 std::cout << "The quence is full." << std::endl; 23 return false; 24 } 25 26 m_pData[m_nTial] = elem; 27 m_nTial = (m_nTial + 1) % m_nMaxSize; 28 VisitQuence(); 29 30 return true; 31 } 32 33 bool CycleQuence::DeleteQuence(ElemType* pElem) //出队 34 { 35 if (IsEmpty()) //队空 36 return false; 37 38 *pElem = m_pData[m_nHead]; 39 m_nHead = (m_nHead + 1) % m_nMaxSize; 40 VisitQuence(); 41 42 return true; 43 } 44 45 void CycleQuence::VisitQuence() const //查看队列元素 46 { 47 std::cout << "The element of quence: "; 48 for (int i = m_nHead, j = 0; j < (m_nTial + m_nMaxSize - m_nHead) % m_nMaxSize; i = (i + 1) % m_nMaxSize, ++j) 49 std::cout << m_pData[i] << ‘ ‘; 50 std::cout << std::endl; 51 }
测试代码(Visual Studio 2017上测试):
1 #include "pch.h" 2 #include "CycleSquence.h" 3 #include <iostream> 4 5 int main() 6 { 7 CycleQuence quence(5); 8 quence.EnterQuence(1); 9 quence.EnterQuence(2); 10 quence.EnterQuence(3); 11 quence.EnterQuence(4); 12 ElemType elem; 13 quence.DeleteQuence(&elem); 14 quence.DeleteQuence(&elem); 15 quence.DeleteQuence(&elem); 16 quence.EnterQuence(5); 17 quence.EnterQuence(6); 18 quence.EnterQuence(7); 19 quence.EnterQuence(8); 20 21 return 0; 22 }
测试结果:
在写VisitQuence()这个方法时,想了好一会儿,就是想可不可以用一个变量遍历队列。但是其实没必要这样,代码在执行效率差不多的情况下,更要注重清晰易懂,简洁的代码有时更容易让人费解。
4 队列的链式存储的实现和关键点
4.1 关键点
1)链队列为空的条件为:head == tial;
2)队列的链式存储通过单链表实现,尤其注意入队、出队操作。
4.2 实现
略。
该篇博客是自己的学习博客,水平有限,如果有哪里理解不对的地方,希望大家可以指正!
原文地址:https://www.cnblogs.com/zpchya/p/10723559.html
时间: 2024-10-12 12:29:54