diff options
| author | Chanin Timbal <[email protected]> | 2024-06-08 12:13:18 -0700 |
|---|---|---|
| committer | Chanin Timbal <[email protected]> | 2024-06-08 12:13:18 -0700 |
| commit | 4dd513935776a7598024fabf57cd003600c887b2 (patch) | |
| tree | 619072de1a93d281fdd95edaf3f31d7c62e0c296 /CST 126/Homework_3/SinglyLinkedList.hpp | |
| parent | Added RemoveLast function and its unit test (diff) | |
| download | homework-1-chaninnohea-4dd513935776a7598024fabf57cd003600c887b2.tar.xz homework-1-chaninnohea-4dd513935776a7598024fabf57cd003600c887b2.zip | |
Completed Functions and Unit tests for Prepend, Insert Before, Insert Afterm Remove Last, and Clear
Diffstat (limited to 'CST 126/Homework_3/SinglyLinkedList.hpp')
| -rw-r--r-- | CST 126/Homework_3/SinglyLinkedList.hpp | 75 |
1 files changed, 75 insertions, 0 deletions
diff --git a/CST 126/Homework_3/SinglyLinkedList.hpp b/CST 126/Homework_3/SinglyLinkedList.hpp index 1b47d99..75f9530 100644 --- a/CST 126/Homework_3/SinglyLinkedList.hpp +++ b/CST 126/Homework_3/SinglyLinkedList.hpp @@ -100,4 +100,79 @@ bool RemoveLast(SinglyLinkedList* list) { return true; } + +bool InsertAfter(SinglyLinkedList* list, ListNode* nodeBefore, ListNode* nodeToInsert) +{ + if (list->_size == 0) + return false; + + ListNode* travel = list->_head; + + while (travel != nodeBefore) + { + travel = travel->_next; + } + + if (travel == nullptr) + return false; + + + nodeToInsert->_next = nodeBefore->_next; + nodeBefore->_next = nodeToInsert; + + return true; +} + +bool InsertBefore(SinglyLinkedList* list, ListNode* node, ListNode* nodeToInsert) +{ + if (list->_size == 0) + return false; + + ListNode* travel = list->_head; + ListNode* temp = list->_head; + + while (travel != node) + { + travel = travel->_next; + } + + while (temp->_next != node) + { + temp = temp->_next; + } + + if (travel == nullptr) + return false; + + nodeToInsert->_next = node; + temp->_next = nodeToInsert; + + return true; +} + + +bool Clear(SinglyLinkedList* list) +{ + if (list->_size == 0) + return true; + + ListNode* travel = list->_head; + ListNode* next = nullptr; + + while (travel != nullptr) + { + next = travel->_next; + delete travel; + travel = next; + } + + list->_head = nullptr; + list->_size = 0; + + return true; +} + + + #endif + |