-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedList.c
100 lines (91 loc) · 1.81 KB
/
linkedList.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
#include "monty.h"
/**
* new_head - adds a node to the beginning of doubly linked list
*
* @head: pointer to the list
* @n: integer value to store in the node
* Return: pointer to the new node;
*/
stack_t *new_head(stack_t **head, const int n)
{
stack_t *new, *trueHead;
new = malloc(sizeof(stack_t));
if (!new)/*malloc failed*/
{
free(new);
dprintf(STDERR_FILENO, "Error: malloc failed\n");
opCommand[3] = "ERROR";
return (NULL);
}
new->prev = NULL;
new->n = n;
if (!*head)/*check if list is empty*/
{
new->next = NULL;
*head = new;
}
else/*connects new to begining*/
{
trueHead = *head;
while (trueHead->prev)/*make sure at actual head*/
trueHead = trueHead->prev;
new->next = trueHead;
trueHead->prev = new;
}
return (new);
}
/**
* freeList - frees all nodes in a doubly linked list
*
* @head: pointer to the list
*/
void freeList(stack_t *head)
{
stack_t *hide, *seek;
if (!head)/*there is no list*/
return;
seek = head;
while (seek->prev)/*find true head*/
seek = seek->prev;
while (seek)/*free each node*/
{
hide = seek;
seek = seek->next;
free(hide);
}
}
/**
* new_tail - adds a node to the end of a doubly linked list
* @head: pointer to the list
* @n: integer value to store in the node
*
* Return: pointer to new node, NULL on failure
*/
stack_t *new_tail(stack_t **head, const int n)
{
stack_t *new, *tail;
new = malloc(sizeof(stack_t));
if (!new)/*malloc failed*/
{
dprintf(STDERR_FILENO, "Error: malloc failed\n");
free(new);
opCommand[3] = "ERROR";
return (NULL);
}
new->n = n;
new->next = NULL;
if (!*head)/*no current nodes*/
{
new->prev = NULL;
*head = new;
}
else/*connect to end of list*/
{
tail = *head;
while (tail->next)/*find the tail*/
tail = tail->next;
tail->next = new;
new->prev = tail;
}
return (new);
}