-
Notifications
You must be signed in to change notification settings - Fork 0
/
list_insert_at.c
executable file
·93 lines (87 loc) · 2.79 KB
/
list_insert_at.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* list_insert_at.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: akharrou <akharrou@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/02/22 19:27:26 by akharrou #+# #+# */
/* Updated: 2019/03/04 13:17:20 by akharrou ### ########.fr */
/* */
/* ************************************************************************** */
/*
** NAME
** list_insert -- inserts a new list element at a certain index.
**
** SYNOPSIS
** #include <../libft.h>
**
** int
** list_insert_at(t_list **head, const void *item, unsigned int i);
**
** PARAMETERS
**
** t_list **head Pointer to a pointer to the
** first element of a list.
**
** const void *item Data that will be stored in
** the new list element.
**
** unsigned int i Index at which the new element
** will be inserted.
**
** DESCRIPTION
** Creates a new list element, storing 'item' as its item, then
** inserts the newly created list element at index 'i' in the list.
**
** If the given index goes past the end of the list, then the newly
** created element is appended to the end of the list.
**
** If the list does not exist the newly created element is made
** to be the first element of the list.
**
** (*head) is made to point to the first element of the list.
**
** RETURN VALUES
** Returns 0 if successful; otherwise -1.
*/
#include "../Includes/list.h"
static void list_insert_elem_at(t_list **head, t_list **new_elem,
unsigned int i)
{
unsigned int index;
t_list *current;
t_list *previous;
index = 0;
current = (*head);
while (i > index)
{
if (!(current->next))
{
current->next = (*new_elem);
return ;
}
previous = current;
current = current->next;
++index;
}
(*new_elem)->next = current;
if (current == (*head))
(*head) = (*new_elem);
else
previous->next = (*new_elem);
}
int list_insert_at(t_list **head, const void *item,
unsigned int i)
{
t_list *new_elem;
if (head && (new_elem = list_newelem(item)))
{
if (*head)
list_insert_elem_at(head, &new_elem, i);
else
(*head) = new_elem;
return (0);
}
return (-1);
}