Skip to content

Commit 8966963

Browse files
committed
876. Middle of the Linkedlist
1 parent d9860a5 commit 8966963

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

middleNode.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* 876. Middle of the Linkedlist
3+
* Topics: LinkedList, Two Points
4+
* Given the head of a singly linked list, return the middle node of the linked list.
5+
* If there are two middle nodes, return the second middle node.
6+
* Definition for singly-linked list.
7+
* class ListNode {
8+
* val: number
9+
* next: ListNode | null
10+
* constructor(val?: number, next?: ListNode | null) {
11+
* this.val = (val===undefined ? 0 : val)
12+
* this.next = (next===undefined ? null : next)
13+
* }
14+
* }
15+
*/
16+
17+
function middleNode(head: ListNode | null): ListNode | null {
18+
let fast = head;
19+
let slow = head;
20+
21+
while (fast?.next) {
22+
slow = slow.next;
23+
fast = fast.next.next;
24+
}
25+
26+
return slow;
27+
};

0 commit comments

Comments
 (0)