-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path7-insert_dnodeint.c
48 lines (46 loc) · 973 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"
#include <stdlib.h>
#include <stdio.h>
/**
* insert_dnodeint_at_index - inserts a new node at a given position
* @h: double pointer to the beginning of the linked list
* @idx: index at which to insert the new node
* @n: data to enter into new node
*
* Return: pointer to the new node, or NULL on failure
*/
dlistint_t *insert_dnodeint_at_index(dlistint_t **h, unsigned int idx, int n)
{
dlistint_t *new, *next, *current;
unsigned int i;
if (h == NULL)
return (NULL);
if (idx != 0)
{
current = *h;
for (i = 0; i < idx - 1 && current != NULL; i++)
current = current->next;
if (current == NULL)
return (NULL);
}
new = malloc(sizeof(dlistint_t));
if (new == NULL)
return (NULL);
new->n = n;
if (idx == 0)
{
next = *h;
*h = new;
new->prev = NULL;
}
else
{
new->prev = current;
next = current->next;
current->next = new;
}
new->next = next;
if (new->next != NULL)
new->next->prev = new;
return (new);
}