-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy path20 may 2020 doubly linked list deletion
129 lines (119 loc) · 2.48 KB
/
20 may 2020 doubly linked list deletion
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
#include <iostream>
using namespace std;
class DoublyLinkedList{
public:
int data;
DoublyLinkedList* next;
DoublyLinkedList* prev;
DoublyLinkedList(int val)
{
this->data=val;
this->next = NULL;
this->prev = NULL;
}
};
DoublyLinkedList *lastnode = NULL;
DoublyLinkedList* addatfront(DoublyLinkedList* head, int val)
{
DoublyLinkedList* newnode = new DoublyLinkedList(val);
if(head == NULL)
{
lastnode = newnode;
return newnode;
}
newnode->next = head;
head->prev = newnode;
return newnode;
}
void print(DoublyLinkedList* head)
{
DoublyLinkedList* curr = head;
while(curr)
{
cout<<curr->data<<" ";
curr= curr->next;
}
}
DoublyLinkedList* removefront(DoublyLinkedList* head)
{
if(head == NULL)
{
cout<<"Linked List is empty\n";
return head;
}
if(head->next == NULL)
{
lastnode = NULL;
delete head;
return NULL;
}
head = head->next;
delete head->prev;
head->prev = NULL;
return head;
}
DoublyLinkedList* removefromlast(DoublyLinkedList* head)
{
if(head == NULL)
{
cout<<"Linked List is empty\n";
return head;
}
if(head->next == NULL)
{
lastnode = NULL;
delete head;
return NULL;
}
lastnode = lastnode->prev;
delete lastnode->next;
lastnode->next= NULL;
return head;
}
DoublyLinkedList* removegivenval(DoublyLinkedList* head, int val)
{
if(head == NULL)
{
cout<<"Linked list is empty\n";
return head;
}
DoublyLinkedList* curr = head;
while(curr && curr->data != val)
{
curr = curr->next;
}
if(curr == NULL)
{
cout<<"Data not found\n";
return head;
}
if(head == curr)
{
head = head->next;
}
if(lastnode == head)
{
lastnode = lastnode->prev;
}
if(curr->prev)
curr->prev->next = curr->next;
if(curr->next)
curr->next->prev = curr->prev;
delete curr;
return head;
}
int main() {
DoublyLinkedList* head = NULL;
// head = removefromlast(head);
head = addatfront(head,10);
head = addatfront(head,20);
head = addatfront(head,30);
head = addatfront(head,40);
head = addatfront(head,50);
head = addatfront(head,60);
// head = removefront(head);
//head = removefromlast(head);
// head = removegivenval(head,20);
head = removegivenval(head,60);
print(head);
}