diff --git a/0x00-challenge/4-delete_dnodeint/delete_dnodeint b/0x00-challenge/4-delete_dnodeint/delete_dnodeint new file mode 100755 index 0000000..1844945 Binary files /dev/null and b/0x00-challenge/4-delete_dnodeint/delete_dnodeint differ diff --git a/0x00-challenge/4-delete_dnodeint/delete_dnodeint_at_index.c b/0x00-challenge/4-delete_dnodeint/delete_dnodeint_at_index.c new file mode 100644 index 0000000..aea4e45 --- /dev/null +++ b/0x00-challenge/4-delete_dnodeint/delete_dnodeint_at_index.c @@ -0,0 +1,53 @@ +#include "lists.h" +#include + +/** + * delete_dnodeint_at_index - Delete a node at a specific index from a list + * + * @head: A pointer to the first element of a list + * @index: The index of the node to delete + * + * Return: 1 on success, -1 on failure + */ +int delete_dnodeint_at_index(dlistint_t **head, unsigned int index) +{ + dlistint_t *saved_head; + dlistint_t *tmp; + unsigned int p; + + if (*head == NULL) + { + return (-1); + } + saved_head = *head; + p = 0; + while (p < index && *head != NULL) + { + *head = (*head)->next; + p++; + } + if (p != index) + { + *head = saved_head; + return (-1); + } + if (0 == index) + { + tmp = (*head)->next; + free(*head); + *head = tmp; + if (tmp != NULL) + { + tmp->prev = NULL; + } + } + else + { + (*head)->prev->next = (*head)->next; + free(*head); + if ((*head)->next) + (*head)->next->prev = (*head)->prev; + *head = saved_head; + } + return (1); +}