队列-线性实现:循环队列
作者:互联网
1 // 2 // Created by geshenglu on 2020/4/14. 3 // 4 5 #ifndef SEQQUEUE_QUEUE_H 6 #define SEQQUEUE_QUEUE_H 7 template <class T> 8 class Queue{ 9 public: 10 virtual bool IsEmpty() const =0; 11 virtual void EnQueue(const T&x)=0; 12 virtual T DeQueue() =0; 13 virtual T GetHead()const =0; 14 virtual ~Queue() {}; 15 }; 16 17 #endif //SEQQUEUE_QUEUE_H
1 // 2 // Created by geshenglu on 2020/4/14. 3 // 4 5 #ifndef SEQQUEUE_SEQQUEUE_H 6 #define SEQQUEUE_SEQQUEUE_H 7 #include "Queue.h" 8 #include <iostream> 9 template <typename T> 10 class SeqQueue :public Queue<T>{ 11 private: 12 T *elem; 13 int maxSize; 14 int front,rear; 15 void doubleSize(); 16 17 public: 18 SeqQueue(int size=10); 19 ~SeqQueue(); 20 virtual bool IsEmpty() const override ; 21 virtual void EnQueue(const T&x)override ; 22 virtual T DeQueue() override ; 23 virtual T GetHead()const override ; 24 void ShowQueue()const; 25 }; 26 27 template <typename T> 28 void SeqQueue<T>::ShowQueue() const 29 { 30 for (int i=front+1;i<=rear;++i) 31 { 32 std::cout << elem[i] << ' '; 33 } 34 std::cout << std::endl; 35 } 36 37 template <typename T> 38 SeqQueue<T>::SeqQueue(int size) { 39 maxSize = size; 40 elem = new T[maxSize]; 41 front = rear = 0; 42 } 43 44 template <typename T> 45 SeqQueue<T>::~SeqQueue() { 46 delete[]elem; 47 } 48 49 template <typename T> 50 void SeqQueue<T>::doubleSize() { 51 T* tmp = elem; 52 std::cout<<"扩展之前:"; 53 ShowQueue(); 54 elem = new T[maxSize * 2]; 55 for (int i = 1; i < maxSize; ++i) 56 elem[i] = tmp[(front + i)%maxSize]; 57 front = 0; 58 rear = maxSize-1; 59 maxSize *= 2; 60 delete tmp; 61 } 62 63 template <typename T> 64 bool SeqQueue<T>::IsEmpty() const { 65 return front == rear; 66 } 67 68 template <typename T> 69 void SeqQueue<T>::EnQueue(const T& x) { 70 if ((rear + 1) % maxSize == front) 71 doubleSize(); 72 rear = (rear+1) % maxSize; 73 elem[rear] = x; 74 } 75 76 template <typename T> 77 T SeqQueue<T>::DeQueue() { 78 front = (front + 1) % maxSize; 79 return elem[front]; 80 } 81 82 template <typename T> 83 T SeqQueue<T>::GetHead()const { 84 return elem[(front + 1) % maxSize]; 85 } 86 #endif //SEQQUEUE_SEQQUEUE_H
1 #include <iostream> 2 #include "SeqQueue.h" 3 int main() { 4 SeqQueue<int> queue(10); 5 queue.EnQueue(12); 6 queue.EnQueue(13); 7 queue.EnQueue(14); 8 queue.EnQueue(15); 9 queue.EnQueue(16); 10 std::cout <<"队头"<< queue.GetHead() << std::endl; 11 queue.ShowQueue(); 12 queue.DeQueue(); 13 queue.ShowQueue(); 14 queue.EnQueue(999); 15 std::cout << "队头" << queue.GetHead() << std::endl; 16 queue.ShowQueue(); 17 return 0; 18 }
标签:const,队列,SeqQueue,virtual,front,循环,template,线性,SEQQUEUE 来源: https://www.cnblogs.com/jiangnansytle/p/12744075.html