From 93a1b5d1ed30a4c10602f0fbd64eda01bc13402b Mon Sep 17 00:00:00 2001
From: ZakyHermawan <zaky.hermawan9615@gmail.com>
Date: Sun, 19 Sep 2021 02:44:08 +0700
Subject: [PATCH] Fix Priority Queue

---
 priorityQueue.c | 35 +++++++++--------------------------
 1 file changed, 9 insertions(+), 26 deletions(-)

diff --git a/priorityQueue.c b/priorityQueue.c
index fd77f01..584c502 100644
--- a/priorityQueue.c
+++ b/priorityQueue.c
@@ -8,6 +8,8 @@ typedef struct Node {
     struct Node* next;
 } Node;
 
+// lowest priority in the first node
+// if some nodes have the same priority with new node, the new node is on the last of the same priority node
 Node* insert(Node* node) {
     int data, priority;
     printf("Masukkan data: "); scanf("%d", &data);
@@ -17,40 +19,21 @@ Node* insert(Node* node) {
     new->priority = priority;
     new->next = NULL;
 
-    Node* first = node;
-
-    if(node == NULL) {
-        return new;
-    }
-
-    int awal = 1;
-    // utilizing short circuit
-    while(node->next != NULL && node->next->priority < priority) {
-        awal = 0;
-        node = node->next;
-    }
+    Node* ptr = node;
 
-    if(awal) {
-        if(node->priority < priority) {
-            node->next = new;
-            return node;
-        }
+    if(node == NULL || node->priority > priority) {
         new->next = node;
         return new;
     }
 
-    if(node->next != NULL) {
-        Node* save = node->next;
-        node->next = new;
-        new->next = save;
-        return first;
+    while(ptr->next != NULL && ptr->next <= priority) {
+        ptr = ptr->next;
     }
 
-    node->next = new;
-    return first;
-
+    new->next = ptr->next;
+    ptr->next = new;
     
-
+    return first;
 
 }
 
-- 
GitLab