-
Notifications
You must be signed in to change notification settings - Fork 0
/
basic_linked_list_functions.c
97 lines (73 loc) · 1.33 KB
/
basic_linked_list_functions.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
#include "monty.h"
/**
* add_node - push or enqueue an element at the beginning of the stack
* @head: pointer to dll
* @n: value to add
* Return: pointer to new node or NULL
*/
stack_t *add_node(stack_t **head, const int n)
{
stack_t *new;
if (!head)
return (NULL);
new = malloc(sizeof(stack_t));
if (new == NULL)
return (NULL);
new->n = n;
new->prev = NULL;
new->next = *head;
if (*head)
(*head)->prev = new;
*head = new;
return (new);
}
/**
* free_stack - free a dll of int
* @head: a pointer to a dll
*/
void free_stack(stack_t *head)
{
stack_t *tmp;
while (head != NULL)
{
tmp = head;
head = head->next;
free(tmp);
}
}
/**
* pop_s - return the node at the beginning
* @head: pointer to a dll
* Return: pointer to the node or NULL
*/
stack_t *pop_s(stack_t **head)
{
stack_t *tmp;
if (!head || !*head)
return (NULL);
tmp = *head;
*head = (*head)->next;
if (*head)
(*head)->prev = NULL;
return (tmp); /*remember to free it*/
}
/**
* dequeue - return the node at the end
* @head: pointer to a dll
* Return: pointer to node or NULL
*/
stack_t *dequeue(stack_t **head)
{
stack_t *h;
if (!head || !*head)
return (NULL);
h = *head;
while (h->next != NULL)
h = h->next;
if (h->prev)
(h->prev)->next = NULL;
else
/*the queue had one element or less*/
*head = NULL;
return (h);
}