-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSLL_delete.cpp
142 lines (128 loc) · 2.71 KB
/
SLL_delete.cpp
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
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node* next;
Node(int data = 0){
this->data = data;
this->next = NULL;
}
~Node(){
cout<<"Deleted: "<<this->data<<endl;
next = NULL;
delete next;
}
};
int len(Node* &head){
Node* temp = head;
int c = 0;
while(temp){
c++;
temp = temp->next;
}
return c;
}
void insertAtHead(Node* &head, int data){
Node* temp = new Node(data);
temp->next = head;
head = temp;
}
void deleteFromHead(Node* &head){
if(head == NULL){
cout<<"LL is empty\n";
return;
}
Node* temp = head;
head = head->next;
delete temp;
}
void deleteFromEnd(Node* &head){
if(head == NULL){
cout<<"LL is empty\n";
return;
}
Node* temp = head, *p = NULL;
while(temp->next){
p = temp;
temp = temp->next;
}
delete temp;
}
void deleteFromMiddle(Node* &head, int index){
if(head == NULL){
cout<<"LL is empty\n";
return;
}
if(index == 0){
deleteFromHead(head);
return;
}
int i = 1;
Node* p = head, *q = NULL;
while(i <= index && p->next){
q = p ;
p = p->next;
i++;
}
q->next = p->next;
delete p;
}
void deleteNode(Node* &head, int pos){
if(head == NULL ){
cout<<"LL is empty\n";
return;
}
// 1] Create a node n point on Head
Node* temp = head;
// if pos == 0 then delete from head;
if(pos == 0){
head = head->next;
delete temp;
}
else{
// find length
int length = len(head);
if(pos >= length){
cout<<"Invalid pos"<<endl;
return ;
}
else{
Node* p = NULL;
int i = 1;
// find pos of node
while(i <= pos){
p = temp;
temp = temp->next;
i++;
}
// logic to delete node
p->next = temp->next;
delete temp;
}
}
}
void print(Node* &head){
Node* temp = head;
while(temp){
cout<<temp->data<<" ";
temp = temp->next;
}
cout<<endl;
}
int main()
{
Node* head = NULL;
insertAtHead(head,60);
insertAtHead(head,50);
insertAtHead(head,40);
insertAtHead(head,30);
insertAtHead(head,20);
insertAtHead(head,10);
cout<<"Length: "<<len(head)<<endl;
deleteNode(head,5);
deleteNode(head,0);
deleteNode(head,2);
print(head);
return 0;
}