顺序队列c++
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了顺序队列c++,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2251字,纯文字阅读大概需要4分钟。
内容图文
![顺序队列c++](/upload/InfoBanner/zyjiaocheng/638/bee95aa5d77c4bbdb67924465458c24e.jpg)
通过数组建立队列
1 #include <iostream> 2 3 using namespace std; 4 5 template<class T> 6 class MyQueue 7 { 8 public: 9 MyQueue(int queuecapacity=10); 10 ~MyQueue(); 11 12 bool IsEmpty() const; 13 T& Front() const; 14 T& Rear() const; 15 void Push(const T& item); 16 void Pop(); 17 private: 18 T *Queue; 19 int myfront; 20 int myrear; 21 int capacity; 22 }; 23 template<class T> 24 inline MyQueue<T>::MyQueue(int queuecapacity):capacity(queuecapacity) 25 { 26 if(capacity<1) throw "capacity must be > 0"; 27 Queue = new T[capacity]; 28 myfront = myrear = 0; 29 } 30 31 template<class T> 32 MyQueue<T>::~MyQueue() 33 { 34 delete[] Queue; 35 } 36 37 template<class T> 38 bool MyQueue<T>::IsEmpty() const 39 { 40 return myfront==myrear; 41 } 42 43 template<class T> 44 T& MyQueue<T>::Front() const 45 { 46 if(IsEmpty()) throw "Queue is empty"; 47 return Queue[(myfront+1) % capacity]; 48 } 49 50 template<class T> 51 T& MyQueue<T>::Rear() const 52 { 53 if(IsEmpty()) throw "Queue is empty"; 54 return Queue[myrear]; 55 } 56 57 template<class T> 58 void MyQueue<T>::Push(const T& item) 59 { 60 if((myrear+1)%capacity==myfront) 61 { 62 T* newQueue = new T[2*capacity]; 63 int start = (myfront+1)%capacity; 64 if(start<2) 65 { 66 copy(Queue+start,Queue+start+capacity-1,newQueue); 67 } 68 else 69 { 70 copy(Queue+start,Queue+capacity,newQueue); 71 copy(Queue,Queue+myrear+1,newQueue+capacity-start); 72 } 73 myfront = 2*capacity-1; 74 myrear = capacity-2; 75 capacity *= 2; 76 delete[] Queue; 77 Queue = newQueue; 78 } 79 myrear = (myrear+1) % capacity; 80 Queue[myrear] = item; 81 } 82 83 template<class T> 84 void MyQueue<T>::Pop() 85 { 86 if(IsEmpty()) throw "Queue is empty"; 87 myfront = (myfront+1) % capacity; 88 Queue[myfront].~T(); // 某课程上说这样写很厉害 89 } 90 91 int main() 92 { 93 MyQueue<char> a(10); 94 a.Push('A'); 95 a.Push('B'); 96 a.Push('C'); 97 a.Push('D'); 98 cout << a.Front() << endl; 99 cout << a.Rear() << endl; 100 a.Pop(); 101 a.Pop(); 102 cout << a.Front() << endl; 103 cout << "Hello world!" << endl; 104 return 0; 105 }
内容总结
以上是互联网集市为您收集整理的顺序队列c++全部内容,希望文章能够帮你解决顺序队列c++所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。