顺序队列

头文件
  1 #ifndef _顺序队列_H
2 #define _顺序队列_H
3
4
5
6 template <class T>
7 class Queue
8 {
9 public:
10 Queue(int queueCapacity=10);
11 bool IsEmpty() const;
12 T& Front() const;//用来读取队首数据,只看不删
13 T& Rear() const;
14 void Push(const T &item);//队尾加
15 void Pop();//队首删
16
17 private:
18
19 T *queue;
20 int front;//记录队首位置
21 int rear;//记录队尾
22 int capacity;
23
24 };
25
26
27 template<class T>
28 Queue<T>::Queue(int queueCapacity):capacity(queueCapacity)//私有成员变量(函数参数)
29 {
30 if(capacity<1) throw "Queue capacity must be > 0";
31 queue = new T[capacity];
32 front = rear = 0;
33 }
34
35
36 template<class T>
37 inline bool Queue<T>::IsEmpty() const
38 {
39
40 return front ==rear;
41 }
42
43
44 template <class T>
45 void Queue<T>::Push(const T &item)
46 {
47
48 /*if(rear == capacity-1)
49 rear = 0;
50 else
51 rear++;*/
52
53
54 if((rear+1)%capacity==front)//判断是否已满
55 {
56
57 //加倍
58 T* newQueue = new T[2*capacity];//创建一个新的动态数组,容量是原来的2倍
59 int start = (front+1) % capacity;
60 if (start<2)//没有回转 no wrap
61 copy(queue+start, queue+start+capacity-1, newQueue);
62 else //wrap
63 {
64
65 copy(queue+start, queue+capacit, ,newQueue);
66 copy(queue,queue+rear+1,newQueue+capacity-start);;
67
68 }
69
70 fornt = 2*capacity - 1;
71 rear = capacity - 2;
72 capacity *=2;
73 delete[] queue;
74 queue = newQueue;
75
76 }
77 rear = (rear +1) % capacity;
78 queue[rear] = item;//保证了front无数据
79 }
80
81
82 template<class T>
83 inline T& Queue<T>::Front() const
84 {
85
86 if(IsEmpty()) throw "Queue is empty. No Front element";
87 return queue[(front+1) % capacity];
88
89 }
90
91 template<class T>
92 inline T& Queue<T>::Rear() const
93 {
94
95 if(IsEmpty()) throw "Queue is empty.No rear element";
96 return queue[rear];
97 }
98
99 template <class T>
100 void Queue<T>::Pop()
101 {
102
103 if(IsEmpty()) throw "Queue is empty. Cannot delete";
104
105 front = (front+1) % capacity;
106
107 queue[front].~T();
108
109 }
110
111
112 #endif
main.cpp
 1 #include <iostream>
2 #include "顺序队列.h"
3
4 using namespace std;
5
6 int main()
7
8 {
9
10 Queue<char> q(5);
11 q.Push('A');
12 q.Push('B');
13 q.Push('C');
14 cout << q.Front() << ", " << q.Rear() << endl;
15 q.Push('D');
16 q.Push('E');
17
18
19 cout << q.Front() << ", " << q.Rear() << endl;
20
21 //q.Pop();
22 //cout << q.Front() << ", " << q.Rear() << endl;
23 q.Push('F');
24 cout << q.Front() << ", " << q.Rear() << endl;
25
26
27 cout << "测试顺序队列" << endl;
28
29
30 return 0;
31
32 }



posted @ 2012-03-27 23:51  uniquews  阅读(216)  评论(0编辑  收藏  举报