-
Notifications
You must be signed in to change notification settings - Fork 0
/
list_funcs2.c
98 lines (84 loc) · 1.7 KB
/
list_funcs2.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
94
95
96
97
98
#include "monty.h"
#include "lists.h"
/**
* insert_dnodeint_at_index - inserts a node at a given index
* in a doubly linked list
* @h: double pointer to the list
* @idx: index of the node to insert
* @n: data to insert
*
* Return: address of the new node, or NULL if it failed
*/
dlistint_t *insert_dnodeint_at_index(dlistint_t **h, unsigned int idx, int n)
{
unsigned int i;
dlistint_t *new;
dlistint_t *temp = *h;
if (idx == 0)
return (add_dnodeint(h, n));
for (i = 0; temp && i < idx; i++)
{
if (i == idx - 1)
{
if (temp->next == NULL)
return (add_dnodeint_end(h, n));
new = malloc(sizeof(dlistint_t));
if (!new || !h)
return (NULL);
new->n = n;
new->next = NULL;
new->next = temp->next;
new->prev = temp;
temp->next->prev = new;
temp->next = new;
return (new);
}
else
temp = temp->next;
}
return (NULL);
}
/**
* add_dnodeint_end - adds a new node at the end of a doubly linked list
* @head: double pointer to the list
* @n: data to insert in the new node
*
* Return: the address of the new element, or NULL if it failed
*/
dlistint_t *add_dnodeint_end(dlistint_t **head, const int n)
{
dlistint_t *new;
dlistint_t *temp = *head;
if (!head)
return (NULL);
new = malloc(sizeof(dlistint_t));
if (!new)
return (NULL);
new->n = n;
new->next = NULL;
if (*head == NULL)
{
new->prev = NULL;
*head = new;
return (new);
}
while (temp->next)
temp = temp->next;
temp->next = new;
new->prev = temp;
return (new);
}
/**
* free_dlistint - frees a doubly linked list
* @head: pointer to the list to free
*/
void free_dlistint(dlistint_t *head)
{
dlistint_t *temp;
while (head)
{
temp = head->next;
free(head);
head = temp;
}
}