順序隊列的c++實現

jopen 9年前發布 | 1K 次閱讀 Java C/C++

順序隊列的初始化及對隊列的操作保存在queue.h中

#ifndef QUEUE_H

define QUEUE_H

template <class T> class Queue { public: Queue(int queuecapacity); bool Isempty(); void Front(); void Rear(); void Push(T item); void Pop(); private: T *queue; int front; int rear; int capacity; };

//利用構造函數初始化順序隊列 template <class T> Queue<T>::Queue(int queuecapacity) { if( queuecapacity<1) { throw "the capacity of queue must be >0"; } else {
queue=new T[queuecapacity]; capacity=queuecapacity; front=rear=0; //犧牲front這個位置,這個位置不放元素 }

}

//元素進隊列 template <class T> void Queue<T>::Push(T item) { if((rear+1)%capacity==front) { throw "the queue is full"; } else { rear=(rear+1)%capacity; queue[rear]=item; } }

//出列 template <class T> void Queue<T>::Pop() {
if(Isempty()) throw "the queue is empty"; front=(front+1)%capacity; }

//判斷隊列是否為空 template <class T> inline bool Queue<T>::Isempty() { return front==rear; }

//隊首元素 template <class T> inline void Queue<T>::Front() { if(!Isempty()) { cout<<"隊首元素為"<< queue[(front+1)%capacity]<<endl; } else { cout<< "the queue is empty"<<endl; } }

//隊尾元素 template <class T> inline void Queue<T>::Rear() { if(!Isempty()) { cout<<"隊尾元素為"<< queue[rear]<<endl; } else { cout<< "the queue is empty"<<endl; } }

endif

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

主函數

include "queue.h"

include<iostream>

using namespace std; int main() { Queue<int> q(10); q.Push(1); q.Push(2); q.Push(3); q.Front(); q.Rear();

q.Pop(); q.Pop(); q.Pop(); q.Front(); q.Rear();

q.Push(4); q.Front(); q.Rear();

system("pause"); return 0; }</pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!