diff --git a/C/Linked-List/Easy List Node algorithms b/C/Linked-List/Easy List Node algorithms new file mode 100644 index 000000000..0cb106d01 --- /dev/null +++ b/C/Linked-List/Easy List Node algorithms @@ -0,0 +1,124 @@ +#include +#include + +typedef struct s_node { + int value; + struct s_node* next; +} ListNode; + +ListNode* get(int index, ListNode* node) { + if (node == nullptr || index < 0) { + return nullptr; + } + + if (index == 0) { + return node; + } + + return get(--index, node->next); +} + +void set(ListNode* node, int index, int value) { + if (node == nullptr || index < 0) { + return; + } + + if (index == 0) { + node->value = value; + return; + } + + set(node->next, --index, value); +} + +void insert_top(ListNode** list, ListNode* node) { + node->next = *list; + *list = node; +} + +void insert_bottom(ListNode* list, ListNode* node) { + if (list->next == nullptr) { + list->next = node; + return; + } + + insert_bottom(list->next, node); +} + +void insert_rec(ListNode* currentNode, ListNode* node, int index) { + if (currentNode == nullptr) { + return; + } + + if (index - 1 == 0) { + node->next = currentNode->next; + currentNode->next = node; + return; + } + + insert_rec(currentNode->next, node, --index); +} + +void insert_to_list(ListNode** list, ListNode* node, const int index) { + if (index < 0) + return; + + if (index == 0) { + insert_top(list, node); + return; + } + + insert_rec(*list, node, index); +} + +void remove_top(ListNode** list) { + ListNode* tempNode = *list; + *list = (*list)->next; + free(tempNode); +} + +void remove_bottom(ListNode* node) { + if (node->next->next == nullptr) { + ListNode* tempNode = node->next; + node->next = nullptr; + free(tempNode); + return; + } + + remove_bottom(node->next); +} + +void remove_rec(ListNode* currentNode, int index) { + if (currentNode == nullptr) { + return; + } + + if (index - 1 == 0) { + ListNode* tempNode = currentNode->next; + currentNode->next = tempNode->next; + free(tempNode); + return; + } + + remove_rec(currentNode->next, --index); +} + +void remove_from_list(ListNode** list, const int index) { + if (index < 0) { + return; + } + + if (index == 0) { + remove_top(list); + return; + } + + remove_rec(*list, index); +} + +ListNode* create_list(const int value) { + ListNode* node = malloc(sizeof(ListNode)); + node->value = value; + node->next = nullptr; + return node; +}