-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path9-insert_nodeint.c
45 lines (36 loc) · 910 Bytes
/
9-insert_nodeint.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
#include "lists.h"
/**
* insert_nodeint_at_index - Inserts a new node to a listint_t
* list at a given position.
* @head: A pointer to the address of the
* head of the listint_t list.
* @idx: The index of the listint_t list where the new
* node should be added - indices start at 0.
* @n: The integer for the new node to contain.
* Return: If the function fails - NULL.
* Otherwise - the address of the new node.
*/
listint_t *insert_nodeint_at_index(listint_t **head, unsigned int idx, int n)
{
listint_t *new, *copy = *head;
unsigned int node;
new = malloc(sizeof(listint_t));
if (new == NULL)
return (NULL);
new->n = n;
if (idx == 0)
{
new->next = copy;
*head = new;
return (new);
}
for (node = 0; node < (idx - 1); node++)
{
if (copy == NULL || copy->next == NULL)
return (NULL);
copy = copy->next;
}
new->next = copy->next;
copy->next = new;
return (new);
}