-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdlinkedlist_2.c
153 lines (132 loc) · 2.47 KB
/
dlinkedlist_2.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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
#include "lists.h"
/**
* get_dnodeint_at_index - gets the nth node of a doubly linked list
* @head: head pointer to the list
* @index: index of the node to return
*
* Return: address of the node, or if it does not exist, NULL
*/
stack_t *get_dnodeint_at_index(stack_t *head, unsigned int index)
{
unsigned int i = 0;
if (!head)
return (NULL);
while (head)
{
if (index == i)
return (head);
head = head->next;
i++;
}
return (NULL);
}
/**
* sum_dlistint - returns the sum of all the data
* of a doubly linked list
* @head: head pointer to the list
*
* Return: sum of the nodes or 0 on empty
*/
int sum_dlistint(stack_t *head)
{
int sum = 0;
while (head)
{
sum += head->n;
head = head->next;
}
return (sum);
}
/**
* insert_dnodeint_at_index - inserts a node at a given index
* in a doubly linked list
* @h: head double pointer to the list
* @idx: index of the node to insert
* @n: int to insert
*
* Return: address of the new node, or NULL if it failed
*/
stack_t *insert_dnodeint_at_index(stack_t **h, unsigned int idx, int n)
{
stack_t *new = malloc(sizeof(stack_t));
stack_t *temp_prev, *temp = *h;
unsigned int i = 0;
if (!new)
erro(4);
new->n = n;
if (idx == 0)
return (add_dnodeint(h, n));
while (temp)
{
if (idx == i)
{
temp->prev->next = new;
new->prev = temp->prev;
new->next = temp;
temp->prev = new;
return (new);
}
temp_prev = temp;
temp = temp->next;
i++;
}
if (!temp && i == idx)
{
temp_prev->next = new;
new->prev = temp_prev;
return (new);
}
free(new);
return (NULL);
}
/**
* delete_dnodeint_at_index - deletes a node in a doubly linked list
* at a given index
* @head: 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(stack_t **head, unsigned int index)
{
stack_t *temp = *head;
unsigned int i = 0;
if (!(*head))
return (-1);
while (temp && i != index)
{
i++;
temp = temp->next;
}
if (!temp)
return (-1);
else if (temp == *head)
{
*head = (*head)->next;
(*head)->prev = NULL;
free(temp);
}
else if (temp->next == NULL)
{
temp->prev->next = NULL;
free(temp);
}
else
{
temp->prev->next = temp->next;
temp->next->prev = temp->prev;
free(temp);
}
return (1);
}
stack_t *reset_dlink(stack_t **h)
{
stack_t *temp;
temp = *h;
while (temp->prev != NULL)
{
temp = temp->prev;
}
*h = temp;
return (*h);
}