-
Notifications
You must be signed in to change notification settings - Fork 0
/
64.LinkedList_deletingFromCircularLinkedList.cpp
92 lines (85 loc) · 1.83 KB
/
64.LinkedList_deletingFromCircularLinkedList.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
#include<iostream>
using namespace std;
struct node{
int data;
node* next;
};
node* create_circular(int arr[],int num){
node* head,*last,*temp;
head=nullptr;
int i=0;
while(i<num){
temp = new node;
temp->data = arr[i];
if(head==nullptr){
head=temp;
head->next = nullptr;
last=head;
} else{
last->next = temp;
last = temp;
last->next = nullptr;
}
i++;
}
last->next = head;
return head;
}
void display(node* p){
node *q=p;
do{
cout<<q->data<<" ";
q = q->next;
}while(q!=p);
cout<<endl;
}
node* insert(node *p,int index,int num){
node* head = p;
node* temp = new node;
//0 being at head;
if(!index){
//head;
while(p->next!=head) p=p->next;
temp->data = num;
p->next = temp;
temp->next = head;
head = temp;
} else{
for(int i=0;i<index-1;i++) p=p->next;
temp->data = num;
temp->next = p->next;
p->next = temp;
}
return head;
}
node* delete_cll(node *p, int index){
//following zeroth index based
node* head=p,*temp;
if(!index){
//head condition
cout<<"deleted "<<head->data<<endl;
while(p->next!=head) p=p->next;
temp = head;
p->next = p->next->next;
delete temp;
head = p->next;
} else{
for(int i=0;i<index-1;i++) p=p->next;
temp = p->next;
p->next = (p->next)->next;
cout<<"deleted "<<temp->data<<endl;
delete temp;
}
return head;
}
int main(){
int a[] = {1,2,3,4,6};
node *l1 = create_circular(a,5);
display(l1);
l1 = insert(l1,0,5);
display(l1);
l1 = delete_cll(l1,0);
display(l1);
l1 = delete_cll(l1,2);
display(l1);
}