-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmyQueue.h
60 lines (53 loc) · 1.47 KB
/
myQueue.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
#pragma once
#include<iostream>
template<class ElemType> class Node {
public:
ElemType data;// data field
Node<ElemType>* next;
Node(ElemType e, Node* t) { // initialize a Node object
this->data = e;
this->next = t;
}
};
template<class ElemType> class Queue {
private:
Node<ElemType>* front; // begin of queue
Node<ElemType>* rear; // end of queue
int size;
public:
Queue() { front = rear = nullptr; size = 0; }
~Queue() { clear(); }
void clear();
bool empty() { return size == 0; } // if empty,return true;
int getSize() { return size; }
bool EnQueue(ElemType item);
bool DeQueue();
void diaplay(); // Diaplay all the elements
ElemType getFront() { return front->data; }
ElemType getRear() { return rear->data; }
};
template<class ElemType> void Queue<ElemType>::clear() {
while (DeQueue());
}
template<class ElemType> bool Queue<ElemType>::EnQueue(ElemType item) { // insert item
Node<ElemType>* tmp = new Node<ElemType>(item, nullptr);
if (front==nullptr) { front = tmp; rear = tmp; }
else { rear->next = tmp; rear = tmp; }
size++;
return true;
}
template<class ElemType>bool Queue<ElemType>::DeQueue() { // remove the first item
if (front == nullptr)return false;
Node<ElemType>* tmp = front;
front = front->next;
delete tmp;
size--;
return true;
}
template<class ElemType> void Queue<ElemType>::diaplay() { // display all the elements and clear
while (!empty()) {
cout << this->getFront(); // get the front element
this->DeQueue();
}
cout << endl;
}