1. 程式人生 > >C++ 用類封裝實現隊列

C++ 用類封裝實現隊列

pan pub pre () turn ear als sin push

  1 #include<stdlib.h> 
  2 #include <iostream>
  3 using std::cout;
  4 using std::endl;
  5 
  6 #define SUM 3 //此處設置隊列的大小,因為隊列節點是 malloc 的空間,一般不用設置隊列上限。但是為了測試方便就加了上限
  7 
  8 typedef struct QNode{
  9     int data;
 10     struct QNode *pNext;
 11 }QNode,*pQNode;
 12 
 13 class Queue{
 14
private: 15 pQNode m_front; 16 pQNode m_rear; 17 int m_sum;//隊列中節點數目 18 public: 19 Queue(); 20 ~Queue(); 21 void push(int x); 22 void pop(); 23 int front(); 24 int back(); 25 bool empty(); 26 bool
full(); 27 }; 28 Queue::Queue(){ 29 m_front = m_rear =(pQNode)malloc(sizeof(QNode)); 30 m_front->pNext = NULL; 31 m_sum = 0; 32 } 33 Queue::~Queue(){//清空隊列 34 pQNode p,q; 35 m_rear = m_front; 36 p = m_front->pNext; 37 m_front->pNext = NULL; 38 while(p){
39 q = p; 40 p = p->pNext; 41 free(q); 42 } 43 free(m_front); 44 } 45 void Queue::push(int x){ 46 if(!full()){ 47 pQNode p =(pQNode)malloc(sizeof(QNode)); 48 p->data = x; 49 p->pNext = NULL; 50 cout<< "進隊列元素是"<< x <<endl; 51 m_rear->pNext = p; 52 m_rear = p; 53 m_sum++; 54 }else{ 55 cout << "隊列已滿" <<endl; 56 } 57 } 58 void Queue::pop(){ 59 60 pQNode tmp;//指向被刪除節點,方便釋放空間&判斷被刪節點是否是對尾節點 61 if(empty()){ 62 cout << "隊列為空,出隊失敗" <<endl; 63 return ; 64 } 65 cout <<"刪除的隊列頭是:" << m_front->pNext->data <<endl; 66 tmp = m_front->pNext; 67 m_front->pNext = tmp->pNext; 68 if(m_rear == tmp){ 69 m_rear = m_front; 70 } 71 free(tmp); 72 m_sum--; 73 } 74 int Queue::front(){ 75 if(empty()){ 76 cout << "隊列為空" <<endl; 77 return -1;//隊列為空 78 }else{ 79 return m_front->pNext->data; 80 } 81 } 82 int Queue::back(){ 83 if(empty()){ 84 cout <<"隊列為空" <<endl; 85 return -1;//隊列為空 86 }else{ 87 return m_rear->data; 88 } 89 } 90 bool Queue::empty(){ 91 if(m_front == m_rear){ 92 return true; 93 }else 94 return false; 95 } 96 bool Queue::full(){ 97 if(m_sum < SUM){ 98 return false; 99 }else 100 return true; 101 } 102 103 int main(){ 104 Queue que; 105 int ret; 106 107 que.pop(); 108 que.push(1); 109 que.push(2); 110 111 que.pop(); 112 if((ret = que.front()) != -1){ 113 cout << "隊列頭元素是:"<< ret <<endl; 114 } 115 if((ret = que.back()) != -1){ 116 cout << "隊列尾元素是:" << ret <<endl; 117 } 118 que.push(3); 119 que.push(4); 120 que.push(5); 121 122 if((ret = que.front()) != -1){ 123 cout << "隊列頭元素是:"<< ret <<endl; 124 } 125 if((ret = que.back()) != -1){ 126 cout << "隊列尾元素是:" << ret <<endl; 127 } 128 129 return 0; 130 131 }

C++ 用類封裝實現隊列