1. 程式人生 > >順序佇列及鏈佇列的基本操作實現

順序佇列及鏈佇列的基本操作實現

一、實驗目的

1、熟練佇列的結構特點,掌握佇列的順序儲存和鏈式儲存結構和實現。

2、 學會使用佇列解決實際問題。

二、實驗內容

自己確定結點的具體資料型別和問題規模:

分別建立一個順序佇列和鏈佇列,實現佇列的入隊和出隊操作。

三、實驗步驟

1、依據實驗內容分別說明實驗程式中用到的資料型別的定義;

2、相關操作的演算法表達;

3、完整程式;

4、總結、執行結果和分析。

5、總體收穫和不足,疑問等。

四、實驗程式碼

1、順序佇列
 1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
#include<iostream>using namespace std;const
int QueueSize=100;class CirQueue{public: CirQueue();//{front=rear=QueueSize-1;} ~CirQueue(){} void EnQueue(int x); int DeQueue(); int GetQueue(); int Empty();private: int data[QueueSize]; int front,rear;};//迴圈佇列入隊EnQueue函式void CirQueue::EnQueue(int x){ if((rear+1)%QueueSize==front)throw"上溢"; rear=(rear+1
)%QueueSize;//隊尾指標在迴圈意義下加1 data[rear]=x;//在隊尾處加入元素}//迴圈隊列出隊DeQueue函式int CirQueue::DeQueue(){ if(rear==front) throw"下溢"; front=(front+1)%QueueSize;//隊頭指標在迴圈意義下加1 return data[front];//讀取並返回出隊前的隊頭元素}//讀取隊頭元素GetQueue函式int CirQueue::GetQueue(){ if(rear==front) throw"下溢"; int i=(front+1)%QueueSize; return data[i];}//建構函式CirQueue::CirQueue(){ front=rear=QueueSize-1;}int CirQueue::Empty(){ if(front==rear) return 1; else return 0;}void main(){ CirQueue q; if(q.Empty()) cout<<"佇列為空"<<"\n"<<endl; else cout<<"佇列非空"<<"\n"<<endl; cout<<"元素88和99執行入隊操作"<<"\n"<<endl; try { q.EnQueue(88); q.EnQueue(99); } catch(char *wrong) { cout<<wrong<<"\n"<<endl; } cout<<"檢視隊頭元素"<<"\n"<<endl; cout<<q.GetQueue()<<"\n"<<endl; cout<<"執行出隊操作"<<"\n"<<endl; try { q.DeQueue(); } catch(char *wrong) { cout<<wrong<<"\n"<<endl; } cout<<"檢視隊頭元素"<<"\n"<<endl; cout<<q.GetQueue()<<"\n"<<endl;}
2、鏈佇列
1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
#include<iostream>using namespace std;struct Node{ int data; Node *next;};class LinkQueue{public: LinkQueue(); ~LinkQueue();//解構函式,釋放鏈佇列中各結點的儲存空間 void EnQueue(int x);//將元素x入隊 int DeQueue();//將隊頭元素出隊 int GetQueue();//取鏈佇列的隊頭元素 int Empty(); private: Node *front, *rear;//隊頭和隊尾元素};LinkQueue::LinkQueue(){ Node *s=NULL; s=new Node; s->next=NULL; front=rear=s;}LinkQueue::~LinkQueue(){ Node *p=NULL; while(front!=NULL) { p=front->next; delete front; front=p; }}void LinkQueue::EnQueue(