📄 data_struct/链队列.cpp
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
template <class T>
struct Node
{
T data;
Node<T> *next;
};
template <class T>
class LinkQueue
{
public:
LinkQueue()
{
front = rear = new Node<T>;
front->next = NULL;
}
~LinkQueue();
void EnQueue(T x);
T DeQueue();
T GetQueue();
bool Empty() { return rear == front; }
private:
Node<T> *front;
Node<T> *rear;
};
template <class T>
LinkQueue<T>::~LinkQueue()
{
while (front)
{
rear = front->next;
delete front;
front = rear;
}
}
template <class T>
void LinkQueue<T>::EnQueue(T x)
{
Node<T> *now = new Node<T>;
now->data = x;
rear->next = now;
rear = now;
rear->next = NULL;
}
template <class T>
T LinkQueue<T>::DeQueue()
{
if (Empty())
throw "空";
Node<T> *now = front->next;
front->next = now->next;
T x = now->data;
if (!(front->next)) // if (rear == now)
rear = front;
delete now;
return x;
}
template <class T>
T LinkQueue<T>::GetQueue()
{
if (Empty())
throw "空";
return front->next->data;
}