-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlist_pop_item_at.c
executable file
·74 lines (70 loc) · 2.35 KB
/
list_pop_item_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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* list_pop_item_at.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: akharrou <akharrou@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/02/25 07:00:41 by akharrou #+# #+# */
/* Updated: 2019/03/04 13:17:20 by akharrou ### ########.fr */
/* */
/* ************************************************************************** */
/*
** NAME
** list_pop_item_at -- pop an item at a specific index.
**
** SYNOPSIS
** #include <../libft.h>
**
** void *
** list_pop_item_at(t_list **head, unsigned int i);
**
** PARAMETERS
**
** t_list **head Pointer to a pointer to the
** first element of a list.
**
** unsigned int i Index at which to pop the
** item.
**
** DESCRIPTION
** Traverses a list until its i'th element is reached, then
** removes it from the list, frees its memory, stitches the
** list back together and returns the popped element's item.
**
** If the popped element is the first element of the list,
** then (*head), after popping, is updated to point
** to the new first element of the list.
**
** RETURN VALUES
** If successful returns the popped item; otherwise NULL.
*/
#include "../Includes/stdlib_42.h"
#include "../Includes/list.h"
void *list_pop_item_at(t_list **head, unsigned int i)
{
void *item;
t_list *current;
t_list *previous;
unsigned int index;
if (head && (*head))
{
index = 0;
current = (*head);
while (i > index++)
{
if (!(current->next))
return (NULL);
previous = current;
current = current->next;
}
if (current == (*head))
(*head) = current->next;
else
previous->next = current->next;
item = current->item;
free(current);
return (item);
}
return (NULL);
}