-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
130 lines (101 loc) Β· 2.18 KB
/
index.js
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
class Node{
constructor(data , next = null){
this.data = data;
this.next = next;
}
}
class SinglyLinkedList {
constructor(head = null){
this.head = head;
this.size = 0;
}
// insert first
insertFirst(data){
let newNode = new Node(data);
newNode.next = this.head;
this.head = newNode;
this.size++;
}
// insert between
insertBetween(data , index){
let newNode = new Node(data);
let temp = this.head;
let i =0;
while(i !=index-1){
temp = temp.next;
i++;
}
newNode.next = temp.next;
temp.next = newNode;
this.size++;
}
// insert end
insertEnd(data){
let newNode = new Node(data);
if(!this.head){
this.head = newNode;
return;
}
let last = this.head;
while(last.next){
last = last.next;
}
last.next = newNode;
this.size++;
}
// get size
getSize(){
return "Size: \t" + this.size;
}
// clear
clear(){
this.head = null;
}
// print list
printList(){
let temp = this.head;
console.log("Traversing Singly LL");
while(temp){
console.log("Element : " + temp.data);
temp = temp.next;
}
}
// sum
sumNodes(){
let sum = 0;
let temp = this.head;
while(temp){
sum += temp.data;
temp = temp.next;
}
return "Sum : \t" + sum;
}
// get first
getFirst(){
return this.head.data;
}
// get last
getLast(){
let last = this.head;
while(last.next){
last = last.next;
}
return last;
}
}
let sl1 = new SinglyLinkedList();
sl1.insertFirst(3);
sl1.insertFirst(3);
sl1.insertFirst(2);
sl1.insertFirst(1);
sl1.insertFirst(1);
// sl1.insertBetween(2 , 2);
// sl1.insertEnd(20);
sl1.printList();
sl1.removeDuplicates();
sl1.printList();
// console.log(sl1.getSize());
// console.log(sl1.sumNodes());
// console.log(sl1.getFirst());
// console.log(sl1.getLast());
// sl1.clear();