Skip to content

Commit daeb515

Browse files
committed
function that inserts a new node at a given position.
1 parent 6c73143 commit daeb515

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#include "lists.h"
2+
3+
/**
4+
* insert_nodeint_at_index - insert a new node at a given position
5+
* @head: pointer to the head ref
6+
* @idx: position to insert node
7+
* @n: variable
8+
*
9+
* Return: the address of the new node, or null if fail
10+
*/
11+
12+
listint_t *insert_nodeint_at_index(listint_t **head, unsigned int idx, int n)
13+
{
14+
listint_t *current;
15+
listint_t *new;
16+
17+
if (head == NULL)
18+
return (0);
19+
new = malloc(sizeof(listint_t));
20+
if (!new)
21+
return (0);
22+
23+
new->next = NULL;
24+
new->n = n;
25+
26+
if (idx == 0)
27+
{
28+
new->next = *head;
29+
(*head) = new;
30+
return (new);
31+
}
32+
33+
current = *head;
34+
35+
while (idx != 1)
36+
{
37+
current = current->next;
38+
--idx;
39+
if (current == NULL)
40+
{
41+
free(new);
42+
return (NULL);
43+
}
44+
}
45+
new->next = current->next;
46+
current->next = new;
47+
48+
return (new);
49+
}

0 commit comments

Comments
 (0)