-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path7-insert_dnodeint.c
48 lines (40 loc) · 1021 Bytes
/
7-insert_dnodeint.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include "lists.h"
/**
* insert_dnodeint_at_index - inserts a new node at a given position.
*
* @h: current node.
* @idx: position where the new node will be inserted.
* @n: data related to the new node.
*
* Return: address of the new node, or NULL if it failed.
*/
dlistint_t *insert_dnodeint_at_index(dlistint_t **h, unsigned int idx, int n)
{
dlistint_t *temp = NULL, *new_node = NULL;
unsigned int counter = 0;
if (h == NULL)
return (NULL);
if (idx == 0)
return (add_dnodeint(h, n));
temp = *h;
while (temp != NULL && temp->prev != NULL)
temp = temp->prev;
while (temp != NULL && counter < idx)
{
counter++;
temp = temp->next;
}
if (temp == NULL && counter == idx)
return (add_dnodeint_end(h, n));
if (temp == NULL && counter < idx)
return (NULL);
new_node = malloc(sizeof(dlistint_t));
if (new_node == NULL)
return (NULL);
new_node->n = n;
new_node->next = temp;
new_node->prev = temp->prev;
temp->prev->next = new_node;
temp->prev = new_node;
return (new_node);
}