-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01-singly-linked-list.js
More file actions
91 lines (79 loc) · 1.75 KB
/
Copy path01-singly-linked-list.js
File metadata and controls
91 lines (79 loc) · 1.75 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
// Node class
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
// Singly Linked List class
class SinglyLinkedList {
constructor() {
this.head = null;
}
insertAtEnd(value) {
let temp = new Node(value);
if (this.head !== null) {
let t1 = this.head;
while (t1.next !== null) {
t1 = t1.next;
}
t1.next = temp;
} else {
this.head = temp;
}
}
insertAtBeg(value){
let temp = new Node(value)
temp.next = this.head
this.head = temp
}
insertAtMid(value, x ){
let temp = new Node(value)
let t1 = this.head
while(t1.next !== null){
if(t1.data == x){
temp.next = t1.next
t1.next = temp
break
}
t1 = t1.next
}
}
deleteLL(value){
let t1 = this.head
let prev = t1
if(t1.data == value){
this.head = t1.next
}
while(t1.next !== null){
if(t1.data == value){
prev.next = t1.next
return
}else{
prev = t1
t1 = t1.next
}
}
if(t1.data == value){
prev.next = null
}
}
printLL() {
let t1 = this.head;
while (t1.next !== null) {
console.log(t1.data);
t1 = t1.next;
}
console.log(t1.data)
}
}
// Create object
let list = new SinglyLinkedList();
list.insertAtEnd(20);
list.insertAtEnd(30);
list.insertAtEnd(50);
list.insertAtEnd(60);
list.insertAtBeg(10)
list.insertAtMid(40,30)
list.deleteLL(50)
list.printLL();