#ifndef SINGLY_LINKED_LIST_HPP #define SINGLY_LINKED_LIST_HPP struct ListNode { int _data = 0; ListNode* _next = nullptr; }; struct SinglyLinkedList { size_t _size; ListNode* _head = nullptr; }; //SinglyLinkedList singlylinkedlist{}; //ListNode listnode{}; // //listnode._data = 1; //singlylinkedlist._head = &listnode; bool Append(SinglyLinkedList* list, ListNode* node) { //if empty if (list->_size == 0) { list->_head = node; list->_size++; return true; } //if not empty ListNode* travel = nullptr; for (travel = list->_head; travel->_next != nullptr;) { travel = travel->_next; } travel->_next = node; list->_size++; return true; } bool Prepend(SinglyLinkedList* list, ListNode* node) { //if empty if (list->_size == 0) { list->_head = node; list->_size++; return true; } //if not empty ListNode* travel = list->_head; list->_head = node; node->_next = travel; list->_size++; return true; } bool RemoveFirst(SinglyLinkedList* list) { if (list->_size == 0) return false; ListNode* first = list->_head; list->_head = list->_head->_next; list->_size--; delete first; return true; } bool RemoveLast(SinglyLinkedList* list) { if (list->_size == 0) return false; /*if (list->_size == 1) { delete list->_head; list->_head = nullptr; list->_size--; return true; } */ ListNode* SecondToLast = list->_head; while (SecondToLast->_next->_next != nullptr) { SecondToLast = SecondToLast->_next; } delete SecondToLast->_next; SecondToLast->_next = nullptr; list->_size--; 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; list->_size++; 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; list->_size++; 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; } bool ExtractFrom(SinglyLinkedList* list, ListNode* NodetoExtract) { if (list->_size == 0 || NodetoExtract == nullptr) return false; if (NodetoExtract == list->_head) { list->_head = NodetoExtract->_next; delete NodetoExtract; list->_size--; return true; } ListNode* NodeBefore = list->_head; while (NodeBefore->_next != NodetoExtract) { NodeBefore = NodeBefore->_next; } NodeBefore->_next = NodetoExtract->_next; delete NodetoExtract; list->_size--; return true; } #endif