generated from filipe1309/shubcogen-template
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathsolution.ts
More file actions
48 lines (39 loc) · 1.1 KB
/
solution.ts
File metadata and controls
48 lines (39 loc) · 1.1 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
export class LinkedList {
value: number;
next: LinkedList | null;
constructor(value: number) {
this.value = value;
this.next = null;
}
}
// Test: make test t=middle-node
function middleNode(linkedList: LinkedList) {
return mySolution1(linkedList);
// return solution1(linkedList);
}
// Complexity (worst-case): time O(n), space O(1)
function mySolution1(linkedList: LinkedList): LinkedList | null {
let slowNode: LinkedList | null | undefined = linkedList;
let fastNode: LinkedList | null = linkedList;
while (fastNode && fastNode.next) {
slowNode = slowNode?.next;
fastNode = fastNode?.next?.next;
}
return slowNode;
}
// Complexity (worst-case): time O(n), space O(1)
function solution1(linkedList: LinkedList): LinkedList | null {
let count = 0;
let currentNode: LinkedList | null = linkedList;
while (currentNode) {
count++;
currentNode = currentNode.next;
}
const middle = Math.floor(count / 2);
currentNode = linkedList;
for (let i = 0; i < middle; i++) {
currentNode = currentNode?.next || null;
}
return currentNode;
}
export default middleNode;