-
Notifications
You must be signed in to change notification settings - Fork 0
/
priorityQueue_unsortedLinkedList.c
163 lines (137 loc) · 2.2 KB
/
priorityQueue_unsortedLinkedList.c
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
#include <stdio.h>
typedef struct _Node {
int key;
struct _Node *link;
}Node;
Node *pQueue = NULL;
int count = 0;
void create();
void destroy();
void print();
int isEmpty();
int isFull();
Node* createNode(int key);
void insert(int key);
void deleteMax();
int searchMax();
int main() {
int idx;
print();
insert(1);
insert(9);
insert(3);
insert(5);
insert(2);
insert(4);
insert(7);
insert(8);
insert(10);
insert(6); // full
insert(12); // full
print();
printf("max = %d\n\n", searchMax());
// 삭제
deleteMax();
print();
deleteMax();
print();
deleteMax();
print();
printf("max = %d\n\n", searchMax());
// 삭제
destroy();
system("pause");
return 0;
}
void create() {
//없음
}
void destroy() {
Node *del;
while (pQueue) {
del = pQueue;
pQueue = pQueue->link;
count--;
free(del);
printf("free node!, remains count=%d\n", count);
}
}
void print() {
Node *nptr = pQueue;
printf("\npriority\t");
nptr = pQueue;
while (nptr) {
printf("%d\t", nptr->key);
nptr = nptr->link;
}
printf("\n\n");
}
int isEmpty() {
return (count == 0);
}
int isFull() {
return 0;
}
Node* createNode(int key) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->key = key;
newNode->link = NULL;
return newNode;
}
void insert(int key) {
Node *newNode;
if (isEmpty()) {
pQueue = createNode(key);
}
else {
newNode = createNode(key);
newNode->link = pQueue;
//다음 노드가 pQueue노드를 가리켜서 newNode 뒤에 연결될 수 있도록 함.
pQueue = newNode;
}
count++;
}
void deleteMax() {
Node *prev = NULL;
Node *max = NULL;
Node *current = NULL;
//pQ가 없는 경우
if (!pQueue) return;
//pQ 노드가 한개인 경우
if (!(pQueue->link)) {
free(pQueue);
pQueue = NULL;
count = 0;
}
//노드가 두개 이상일 경우
else {
max = pQueue;
prev = NULL;
current = pQueue;
while (current->link) {
if (max->key < current->link->key) {
prev = current;
max = current->link;
}
current = current->link;
}
if (prev == NULL) {
pQueue = max->link;
}
else {
prev->link = max->link;
}
free(max);
count--;
}
}
int searchMax() {
int max = -1;
Node *nptr = pQueue;
while (nptr) {
if (nptr->key > max)
max = nptr->key;
nptr = nptr->link;
}
return max;
}