forked from ravya1108/hactoberfest2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
circular linked list deletion.cpp
94 lines (88 loc) · 1.67 KB
/
circular linked list deletion.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
#include<iostream>
using namespace std;
class node{
public:
int data;
node *next;
node(int d){
data=d;
next=NULL;
}
};
void insertion_at_head(node *&head,int data){
//1.create a new node
node *n=new node(data);
node *temp=head;
n->next=head;
//2.if list is not empty than traverse the list till last node and updat the pointer of last node to the new node
if(temp!=NULL){
while(temp->next!=head){
temp=temp->next;
}
temp->next=n;
}
//if list is empty then new node poins to itself
else{
n->next=n;
}
//update head to new node
head=n;
}
void print(node *head){
node *temp=head;
while(temp->next!=head){
cout<<temp->data<<" ";
temp=temp->next;
}
cout<<temp->data<<" ";
}
//search function
node * search(node *head,int data){
node *temp=head;
while(temp->next!=head){
if(temp->data==data){
return temp;
}
temp=temp->next;
}
//for last node
if(temp->data==data){
return temp;
}
return NULL;
}
//delete function
void delete_node(node *&head,int data){
node *del=search(head,data);
//if node is not present
if(del==NULL){
return;
}
//if del(node to be deleted) is head node
if(head==del){
head=head->next;
}
//if del is present
node *temp=head;
//go till one step before of del
while(temp->next!=del){
temp=temp->next;
}
temp->next=del->next;
delete del;
}
int main(){
node *head=NULL;
insertion_at_head(head,1);
insertion_at_head(head,2);
insertion_at_head(head,3);
insertion_at_head(head,4);
print(head);
cout<<endl;
delete_node(head,3);
print(head);
cout<<endl;
delete_node(head,1);
print(head);
return 0;
}