Skip to content

Commit 0a0ef4c

Browse files
author
baochau.dinh
committed
js-concepts: leetcode prob.876 - middle of the linked list
1 parent 870e071 commit 0a0ef4c

File tree

1 file changed

+30
-0
lines changed
  • LeetCode/876. Middle of the Linked List

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* Given the head of a singly linked list, return the middle node of the linked list
3+
*/
4+
5+
function ListNode(val, next = null) {
6+
this.val = (val === undefined ? 0 : val);
7+
this.next = (next === undefined ? null : next);
8+
}
9+
10+
var middleNode = function(head) {
11+
let length = 0;
12+
let current = head;
13+
while (current !== null) {
14+
length++;
15+
current = current.next;
16+
}
17+
18+
let middleIdx = Math.floor(length / 2);
19+
current = head;
20+
let currIdx = 0;
21+
while (currIdx < middleIdx) {
22+
currIdx++;
23+
current = current.next;
24+
}
25+
26+
return current;
27+
}
28+
29+
const listNode = new ListNode(1);
30+
console.log(middleNode(listNode));

0 commit comments

Comments
 (0)