-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeletion.c
More file actions
executable file
·106 lines (84 loc) · 1.75 KB
/
deletion.c
File metadata and controls
executable file
·106 lines (84 loc) · 1.75 KB
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 "linked_list.h"
node *delete_first(node *head)
{
if (!head)
return NULL;
/*Special case: Only one node in the list*/
if (!head->next)
{
free(head);
return NULL;
}
node *temp = head;
head = head->next;
if (head)
head->prev = NULL;
free(temp);
return head;
}
node *delete_end(node *head)
{
if (!head)
return NULL;
/*Special case: Only one node in the list*/
if (!head->next)
{
free(head);
return NULL;
}
node *ptr = head;
while (ptr->next->next)
ptr = ptr->next;
free(ptr->next);
ptr->next = NULL;
return head;
}
node *delete_pos(node *head, int pos)
{
node *ptr = NULL;
if (pos < 0 || !head)
{
printf("Invalid position or empty list\n");
return head;
}
if (pos == 0)
{
if (!head->next)
{
free(head);
return NULL;
}
node *temp = head;
head = head->next;
if (head)
head->prev = NULL;
free(temp);
return head;
}
else if (pos == count_nodes(head))
{
ptr = head;
while (ptr->next->next)
ptr = ptr->next;
free(ptr->next);
ptr->next = NULL;
return head;
}
else
{
ptr = head;
for (int i = 0; i < pos - 1 && ptr; i++)
ptr = ptr->next;
if (!ptr || !ptr->next)
{
printf("Invalid position\n");
return head;
}
node *temp = ptr->next;
ptr->next = temp->next;
if (temp->next)
temp->next->prev = ptr;
free(temp);
return head;
}
}