[C++]資料結構:鏈表描述的隊列LinkedQueue類

來源:互聯網
上載者:User
//鏈表描述的隊列類LinkedQueue#include <iostream>using namespace std;template <class T>class Node{public:T data;Node<T> *link;};//FIIFO對象template <class T>class LinkedQueue{public:LinkedQueue(){front=rear=0;}~LinkedQueue();bool IsEmpty()const{return ((front)?false:true);}bool IsFull()const;T First()const;//返回隊首元素T Last()const;//返回隊尾元素LinkedQueue<T>& Add(const T& x);LinkedQueue<T>& Delete(T& x);void Output();Node<T> *front;//指向第一個節點Node<T> *rear;//最後一個節點};template <class T>LinkedQueue<T>::~LinkedQueue(){Node<T> *next;while (front){next = front->link;delete front;front = next;}}class OutOfBounds{          public:              OutOfBounds(){              cout<<"Out Of Bounds!"<<endl;              }      };              //記憶體不足的異常類      class NoMem{          public:              NoMem(){                  cout<<"No Memory!"<<endl;              }      };  //該隊列的輸出方法template<class T>void LinkedQueue<T>::Output(){Node<T> *temp = front;while(temp){cout<<temp->data<<" ";temp=temp->link;}cout<<""<<endl;}//判斷當前隊列是否已滿template <class T>bool LinkedQueue<T>::IsFull()const{Node<T>*p;try{p = new Node<T>;delete p;return false;}catch (NoMem){return true;}}//返回隊列的第一個元素template <class T>T LinkedQueue<T>::First()const{if(IsEmpty())throw OutOfBounds();return front->data}//返回隊列的最後一個元素template <class T>T LinkedQueue<T>::Last()const{if(IsEmpty())throw OutOfBounds();return rear->data}//將x添加到隊列的尾部template<class T>LinkedQueue<T>& LinkedQueue<T>::Add(const T&x){Node<T>*p = new Node<T>;p->data=x;p->link=0;//在隊列尾部添加新節點if (front){rear->link = p;} else{front=p;}rear=p;return *this;}//刪除第一個元素並將其放到X中去template<class T>LinkedQueue<T>& LinkedQueue<T>::Delete(T&x){if (IsEmpty()){throw OutOfBounds();}x = front->data;Node<T>*p = front;front = front->link;delete p;return *this;}void main(){LinkedQueue<int>myQueue;myQueue.Add(5);myQueue.Add(2);myQueue.Add(0);myQueue.Add(1);myQueue.Add(3);myQueue.Add(1);myQueue.Add(4);myQueue.Output();int temp;myQueue.Delete(temp);myQueue.Delete(temp);myQueue.Delete(temp);myQueue.Output();}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.