-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path03-single-circular-linked-list.js
More file actions
118 lines (106 loc) · 2.48 KB
/
Copy path03-single-circular-linked-list.js
File metadata and controls
118 lines (106 loc) · 2.48 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
107
108
109
110
111
112
113
114
115
116
117
118
class Node{
constructor(data){
this.data = data
this.head = null
}
}
class circularSingleLinkedlist{
constructor(){
this.head = null
}
InsertAtEnd(value){
let temp = new Node(value)
if(this.head !== null){
let t1 = this.head
while(t1.next !== this.head){
t1 = t1.next
}
t1.next = temp
temp.next = this.head
}else{
this.head = temp
temp.next = this.head
}
}
InsertAtBeg(value){
let temp = new Node(value)
// for empty list
if(this.head == null){
this.head = temp
temp.next = this.head
return
}
// for non-empty list
let t1 = this.head
if(this.head !== null){
while(t1.next!== this.head){
t1 = t1.next
}
temp.next = this.head
t1.next = temp
this.head = temp
}
}
InsertAtMid(value,x){
let temp = new Node(value)
let t1 = this.head
while(t1.next !== this.head){
if(t1.data == x){
temp.next = t1.next
t1.next = temp
return
}
t1 = t1.next
}
}
deleteCircularLL(value){
let t1 = this.head
let prev = t1
// Head delete case
if(this.head.data == value){
// Single node case
if(t1.next === this.head){
this.head = null
return
}
// Find last node
let last = this.head
while(last.next !== this.head){
last = last.next
}
this.head = t1.next
last.next = this.head
return
}
while(t1.next !== this.head){
if(t1.data == value){
prev.next = t1.next
return
}else{
prev = t1
t1 = t1.next
}
}
if(t1.data == value){
prev.next = this.head
}
}
printLL(){
let t1 = this.head
while(t1.next !== this.head){
console.log(t1.data)
t1 = t1.next
}
console.log(t1.data)
}
}
let Circularlist = new circularSingleLinkedlist()
Circularlist.InsertAtEnd(20)
Circularlist.InsertAtEnd(40)
Circularlist.InsertAtEnd(60)
Circularlist.InsertAtBeg(10)
Circularlist.InsertAtBeg(30)
Circularlist.InsertAtBeg(70)
Circularlist.InsertAtMid(50,40)
Circularlist.deleteCircularLL(30)
Circularlist.printLL()