-
Notifications
You must be signed in to change notification settings - Fork 0
/
7-insert_dnodeint.c
52 lines (50 loc) · 1.09 KB
/
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
49
50
51
52
#include "lists.h"
/**
* insert_dnodeint_at_index - inserts node at index
* @h: head of node
* @idx: index to insert node
* @n: data for new node
* Return: list with inserted node
*/
dlistint_t *insert_dnodeint_at_index(dlistint_t **h, unsigned int idx, int n)
{
unsigned int count = 1;
dlistint_t *temp = NULL, *new = NULL;
new = malloc(sizeof(dlistint_t));
if (new == NULL || h == NULL)
return (NULL);
new->n = n;
temp = *h;
if (idx == 0)
{
*h = new;
new->next = temp;
new->prev = NULL;
temp->prev = new;
return (new);
}
while (temp->next != NULL)
{
if (count == idx) /* found back */
{
new->prev = temp; /* current prev to back link */
new->next = temp->next; /* current next to front link*/
temp->next = new; /* back next link */
new->next->prev = new; /* from prev link */
}
temp = temp->next;
count++;
}
if (count == idx) /* end of DLL */
{
new->prev = temp; /* current prev to back link */
new->next = NULL; /* current next to NULL*/
temp->next = new; /* back next link */
}
if (count < idx)
{
free(new);
return (NULL);
}
return (new);
}