Sergei G / LinkedList

Dependents:   JobScheduler

Fork of LinkedList by Sam Grove

Revision:
8:918b196b0ac4
Parent:
7:4ed66162aaa8
Child:
11:4336cd18cce9
--- a/LinkedList.cpp	Sun Feb 23 14:09:48 2014 +0000
+++ b/LinkedList.cpp	Fri Jul 07 23:29:29 2017 +0000
@@ -58,35 +58,54 @@
     return _head;
 }
 
-//template<class retT>
-//retT *LinkedList<retT>::insert(void *data, uint32_t loc)
-//{
-//    retT *new_node = new retT [1];
-//    // make sure the new object was allocated
-//    if (0 == new_node)
-//    {
-//        error("Memory allocation failed\n");
-//    }
-//    retT *current = _head->next;
-//    retT *prev = _head;
-//    // move to the item we want to insert
-//    for (uint32_t i=1; i!=(loc-1); i++)
-//    {
-//        prev = current;
-//        current = current->next;
-//    }
-//    // store the address to the linked datatype
-//    new_node->data = data;
-//    // clear the next pointer
-//    new_node->next = 0;
-//    // update the list and store the new stuff
-//    prev->next = new_node;
-//    new_node->next = current;
-//    // store the address to the linked datatype
-//    _head->data = data;
-//
-//    return prev->next;
-//}
+template<class retT>
+retT *LinkedList<retT>::insertAsc(void *data, bool (isBigger)(void* data1, void *data2))
+{
+    retT *new_node = new retT [1];
+    // make sure the new object was allocated
+    if (0 == new_node)
+    {
+        error("Memory allocation failed\n");
+    }
+    // store the address to the linked datatype
+    new_node->data = data;
+    // clear the next pointer
+    new_node->next = 0;
+    // check for an empty list
+    if (0 == _head)
+    {
+        _head = new_node;
+        printf("[insertAsc] set as head\n");
+        return new_node;
+    }
+
+    retT *current = _head;
+    retT *prev = 0;
+    // move to the item we want to insert
+    while (isBigger(data, current->data))
+    {
+        // while(true) execute the following
+        // data being inserted is smaller than current->data
+        if (0 == current->next) {
+            // there is no more data
+            printf("[insertAsc] insert at end\n");
+            current->next = new_node;
+            return new_node;
+        }
+        prev = current;
+        current = current->next;
+    }
+    if (0 == prev) {
+        printf("[insertAsc] insert at start\n");
+        new_node->next = _head;
+        _head = new_node;    
+        return new_node;
+    }
+    printf("[insertAsc] insert inside\n");
+    new_node->next = current;
+    prev->next = new_node;
+    return new_node;
+}
 
 template<class retT>
 retT *LinkedList<retT>::append(void *data)