-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueue.h
More file actions
117 lines (103 loc) · 1.75 KB
/
Queue.h
File metadata and controls
117 lines (103 loc) · 1.75 KB
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
108
109
110
111
112
113
114
#pragma once
#include<iostream>
using namespace std;
template<typename T>
class Queue
{
struct Node
{
T num;
int priority;
Node* next;
};
Node* head;
Node* tail;
public:
Queue();
bool isEmpty();
void push(T, int);
T pop();
void show() const;
~Queue();
};
template<typename T>
inline Queue<T>::Queue()
{
this->head = nullptr;
this->tail = nullptr;
}
template<typename T>
inline bool Queue<T>::isEmpty()
{
return this->head == nullptr;
}
template<typename T>
inline void Queue<T>::push(T val, int priority)
{
Node* newNode = new Node;
newNode->num = val;
newNode->priority = priority;
newNode->next = nullptr;
if (isEmpty())
this->head = this->tail = newNode;
else if(head && newNode->priority > this->head->priority)
{
Node* nodePtr = this->head;
this->head = newNode;
newNode->next = nodePtr;
}
else
{
Node* nextNode = this->head;
Node* previusNode = nullptr;
while (nextNode && priority <=nextNode->priority)
{
previusNode = nextNode;
nextNode = nextNode ->next;
}
if (previusNode == nullptr)
{
this->tail->next = newNode;
this->tail = newNode;
}
else
{
previusNode->next = newNode;
newNode->next = nextNode;
}
}
}
template<typename T>
inline T Queue<T>::pop()
{
if (isEmpty())
{
cout << "Queue is empty.\n";
exit(1);
}
Node* nodePtr = this->head;
T num = nodePtr->num;
this->head = this->head->next;
if (!this->head)
{
this->head = this->tail = nullptr;
}
delete nodePtr;
return num;
}
template<typename T>
inline void Queue<T>::show() const
{
Node* nodePtr = head;
while (nodePtr) {
cout << "(" << nodePtr->num << ", " << nodePtr->priority << ") \t";
nodePtr = nodePtr->next;
}
cout << "\n";
}
template<typename T>
inline Queue<T>::~Queue()
{
while (!isEmpty())
pop();
}