-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path7-insert_dnodeint.c
47 lines (46 loc) · 954 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
#include "lists.h"
/**
* insert_dnodeint_at_index - insert node at a position
* @h: The head of list
* @idx: The index, starting at 0
* @n: The value of new node
* Return: The 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 *actnode = *h;
dlistint_t *nnode;
unsigned int con;
if (!h)
return (NULL);
if (*h == NULL && idx != 0)
return (NULL);
nnode = malloc(sizeof(dlistint_t));
if (nnode == NULL)
return (NULL);
nnode->n = n;
if (idx == 0)
{
if (*h)
actnode->prev = nnode;
*h = nnode;
nnode->prev = NULL;
nnode->next = actnode;
return (nnode);
}
for (con = 1; con < idx; con++)
{
actnode = actnode->next;
if (actnode == NULL)
{
free(nnode);
return (NULL);
}
}
nnode->prev = actnode;
nnode->next = actnode->next;
if (actnode->next)
actnode->next->prev = nnode;
actnode->next = nnode;
return (nnode);
}