-
Notifications
You must be signed in to change notification settings - Fork 2
/
dlinkedlist_1.c
106 lines (88 loc) · 1.67 KB
/
dlinkedlist_1.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
#include "monty.h"
#include "lists.h"
/**
* dlistint_len - returns the number of elements
* in a doubly linked list
* @h: head pointer to the list
*
* Return: number of elements
*/
size_t dlistint_len(const stack_t *h)
{
size_t i = 0;
while (h)
{
i++;
h = h->next;
}
return (i);
}
/**
* add_dnodeint - adds a new node at the
* beginning of a doubly linked list
* @head: head double pointer to the list
* @n: int data to insert in the new node
*
* Return: the address of the new element, or NULL if it failed
*/
stack_t *add_dnodeint(stack_t **head, const int n)
{
stack_t *new = malloc(sizeof(stack_t));
if (!new)
erro(4);
new->n = n;
if (!(*head))
{
*head = new;
new->next = NULL;
new->prev = NULL;
return (new);
}
new->next = *head;
new->prev = NULL;
(*head)->prev = new;
*head = new;
return (new);
}
/**
* add_dnodeint_end - adds a new node at the end
* of a doubly linked list
* @head: head double pointer to the list
* @n: int data to insert in the new node
*
* Return: the address of the new element, or NULL if it failed
*/
stack_t *add_dnodeint_end(stack_t **head, const int n)
{
stack_t *last = *head;
stack_t *new = malloc(sizeof(stack_t));
if (!new)
return (NULL);
new->n = n;
new->next = NULL;
if (!(*head))
{
*head = new;
new->prev = NULL;
return (new);
}
while (last->next)
last = last->next;
last->next = new;
new->prev = last;
return (*head);
}
/**
* free_dlistint - frees a doubly linked list
* @head: head pointer to the list
*/
void free_dlistint(stack_t *head)
{
stack_t *temp;
while (head)
{
temp = head->next;
free(head);
head = temp;
}
}