-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlist_funcs1.c
executable file
·139 lines (114 loc) · 2.17 KB
/
list_funcs1.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#include "monty.h"
/**
* dlistint_len - returns the number of nodes in a doubly linked list
* @h: pointer to the list
*
* Return: number of nodes
*/
size_t dlistint_len(const dlistint_t *h)
{
size_t nodes = 0;
if (!h)
return (0);
while (h)
{
nodes++;
h = h->next;
}
return (nodes);
}
/**
* add_dnodeint - adds a new node at the beginning 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(dlistint_t **head, const int n)
{
dlistint_t *new;
if (!head)
return (NULL);
new = malloc(sizeof(dlistint_t));
if (!new)
return (NULL);
new->n = n;
new->next = *head;
new->prev = NULL;
if (*head)
(*head)->prev = new;
*head = new;
return (new);
}
/**
* print_dlistint - prints a doubly linked list
* @h: pointer to the list
*
* Return: number of nodes in the list
*/
size_t print_dlistint(const dlistint_t *h)
{
size_t nodes = 0;
if (!h)
return (0);
while (h)
{
printf("%d\n", h->n);
h = h->next;
nodes++;
}
return (nodes);
}
/**
* delete_dnodeint_at_index - deltes a node in a doubly linked list
* at a given index
* @head: double pointer to the list
* @index: index of the node to delete
*
* Return: 1 on success, -1 on failure
*/
int delete_dnodeint_at_index(dlistint_t **head, unsigned int index)
{
dlistint_t *temp = *head;
unsigned int i = 0;
if (!index)
{
(*head) = temp->next;
if (temp->next)
temp->next->prev = NULL;
temp->next = NULL;
free(temp);
return (1);
}
while (i < index)
{
temp = temp->next;
i++;
if (!temp)
return (0);
}
temp->prev->next = temp->next;
if (temp->next)
temp->next->prev = temp->prev;
free(temp);
return (1);
}
/**
* get_dnodeint_at_index - gets the nth node of a doubly linked list
* @head: pointer to the list
* @index: index of the node to return
*
* Return: address of the node, or if it does not exist, NULL
*/
dlistint_t *get_dnodeint_at_index(dlistint_t *head, unsigned int index)
{
unsigned int i = 0;
if (!head)
return (NULL);
while (head && i < index)
{
head = head->next;
i++;
}
return (head ? head : NULL);
}