-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path102-free_listint_safe.c
70 lines (61 loc) · 1.2 KB
/
102-free_listint_safe.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
#include "lists.h"
#include <stdlib.h>
#include <stdio.h>
/**
* _ra - reallocates memory for an array of pointers
* to the nodes in a linked list
* @list: the old list to append
* @size: size of the new list (always one more than the old list)
* @new: new node to add to the list
*
* Return: pointer to the new list
*/
listint_t **_ra(listint_t **list, size_t size, listint_t *new)
{
listint_t **newlist;
size_t i;
newlist = malloc(size * sizeof(listint_t *));
if (newlist == NULL)
{
free(list);
exit(98);
}
for (i = 0; i < size - 1; i++)
newlist[i] = list[i];
newlist[i] = new;
free(list);
return (newlist);
}
/**
* free_listint_safe - frees a listint_t linked list.
* @head: double pointer to the start of the list
*
* Return: the number of nodes in the list
*/
size_t free_listint_safe(listint_t **head)
{
size_t i, num = 0;
listint_t **list = NULL;
listint_t *next;
if (head == NULL || *head == NULL)
return (num);
while (*head != NULL)
{
for (i = 0; i < num; i++)
{
if (*head == list[i])
{
*head = NULL;
free(list);
return (num);
}
}
num++;
list = _ra(list, num, *head);
next = (*head)->next;
free(*head);
*head = next;
}
free(list);
return (num);
}