-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlist_pop_item.c
executable file
·79 lines (75 loc) · 2.81 KB
/
list_pop_item.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* list_pop_item.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: akharrou <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/02/25 07:33:51 by akharrou #+# #+# */
/* Updated: 2019/06/08 14:05:49 by akharrou ### ########.fr */
/* */
/* ************************************************************************** */
/*
** NAME
** list_pop_item -- pop an item that matches a specific reference.
**
** SYNOPSIS
** #include <../libft.h>
**
** void *
** list_pop_item(t_list **head, const void *item_ref,
** int (*cmp)(const void *, const void *));
**
** PARAMETERS
**
** t_list **head Pointer to a pointer to the
** first element of a list.
**
** const void *item_ref Reference to find the item.
**
** int (*cmp)(void *, void *) A pointer to a comparasion
** function. It compares the
** item reference to the current
** item. Returns 0 for a match.
**
** DESCRIPTION
** Traverses a list until the 'item_ref' matches the current
** element's item, according to the comparasion function, then
** removes the element 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(t_list **head, const void *item_ref,
int (*cmp)(const void *, const void *))
{
void *item;
t_list *current;
t_list *previous;
if (head && *head && item_ref && cmp)
{
current = (*head);
while (cmp((void *)item_ref, current->item) != 0)
{
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);
}