-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathQueue.h
107 lines (97 loc) · 1.82 KB
/
Queue.h
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
#ifndef QUEUE
#define QUEUE
#include <iostream>
#include <stdlib.h>
#include "templateNode.h"
using namespace std;
template<class T>
class Queue
{
private:
Node<T> *head;
Node<T> *tail;
void memoryError()
{
cerr << "Memory Error!\n";
exit(-1);
}
void emptyError()
{
cerr << "Queue is empty!\n";
exit(-1);
}
public:
Queue()
{
head = new Node<T>();
if(head == NULL)
memoryError();
tail = head;
}
Queue(T *a,int length)
{
head = new Node<T>();
if(head == NULL)
memoryError();
tail = head;
Node<T> *s;
for(int i = 0;i < length; ++i)
{
s = new Node<T>();
if(s == NULL)
memoryError();
s->data = a[i];
tail->next = s;
tail = s;
}
}
~Queue()
{
Node<T> *s = NULL;
while (head)
{
s = head;
head = head->next;
delete s;
}
}
bool isEmpty()
{
return head == tail;
}
//大小
int size()
{
int count = 0;
Node<T> *s = head;
while (s = s->next)
{
++count;
}
return count;
}
//插入
void push(T value)
{
Node<T> *s = new Node<T>();
if(s == NULL)
memoryError();
s->data = value;
tail->next = s;
tail = s;
}
//弹出首个元素 (先进先出)
T pop()
{
if(isEmpty())
emptyError();
Node<T> *s = head->next;
T value = s->data;
head->next = s->next;
if(head->next == NULL) //若只剩一个元素 更改尾指针
tail = head;
delete s;
return value;
}
};
#endif