顺序队列的c++实现
发布时间:2020-05-24 21:30:51 所属栏目:Java 来源:互联网
导读:顺序队列的c++实现
|
下面是脚本之家 jb51.cc 通过网络收集整理的代码片段。 脚本之家小编现在分享给大家,也给大家做个参考。 #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;
}
以上是脚本之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。 如果觉得脚本之家网站内容还不错,欢迎将脚本之家网站推荐给程序员好友。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
