-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSplit a Linked List.js
More file actions
58 lines (46 loc) · 883 Bytes
/
Split a Linked List.js
File metadata and controls
58 lines (46 loc) · 883 Bytes
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
/*
Given a linked list,
write a function to split the list into two equal halves.
*/
log = console.log;
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
}
add(value) {
const node = new Node(value);
if (!this.head) {
this.head = node;
return this.head;
}
let p = this.head;
while (p.next) p = p.next;
p.next = node;
return node;
}
splitInHalf() {
let hare = this.head;
let turtle = this.head;
while (hare) {
hare = hare.next;
if (!hare) break;
turtle = turtle.next;
hare = hare.next;
}
const toReturn = { ...turtle };
turtle.next = null;
return toReturn;
}
}
const List = new LinkedList();
List.add(1);
List.add(2);
List.add(3);
List.add(4);
log(List.splitInHalf());