-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkth.js
More file actions
94 lines (89 loc) · 1.78 KB
/
kth.js
File metadata and controls
94 lines (89 loc) · 1.78 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
class Node {
constructor(data,next = null){
this.data = data;
this.next = next;
}
}
class LinkedList{
constructor(){
this.head = null;
this.size = null;
}
insertFirst(data){
const node = new Node(data,this.head)
this.head = node;
this.size++
}
getFirst(){
return this.head
}
getLast(){
if (!this.head){
return null;
} else {
let node = this.head;
while(node.next){
node = node.next
}
return node;
}
}
print(){
var node = this.head;
console.log('start of linked list');
while (node !== null) {
console.log(node.data);
node = node.next;
}
console.log('end of linked list');
}
kth(index){
var counter = 0;
var node = this.head;
var cool = this.head
while(node){
counter++
node = node.next;
}
var find = counter - index;
counter = 0;
while(cool){
if (counter === find){
return cool;
}
counter++
cool = cool.next
}
}
removeDuplicates(){
let curr = this.head.next
let prev = this.head;
var hash = {};
if (prev){
hash[prev.data] = 1;
}
while (curr){
if (!hash[curr.data]){
hash[curr.data] = 1;
prev = curr;
curr = curr.next;
} else {
var store = curr.next;
prev.next = store;
curr = store;
}
}
return hash;
}
}
var LL = new LinkedList();
LL.insertFirst(8)
LL.insertFirst(7)
LL.insertFirst(6)
LL.insertFirst(6)
LL.insertFirst(5)
LL.insertFirst(4)
LL.insertFirst(3)
LL.insertFirst(2)
LL.insertFirst(1)
console.log(LL.kth(5))