LeetCode: Middle of the Linked List Solution

Several ways

Approach: Calculate Length

Calculate list length

Iterate to the middle

Implementation

1var middleNode = function (head) {
2 let n = 0
3
4 let iter = head
5 while (iter) {
6 n++
7 iter = iter.next
8 }
9
10 let mid = Math.floor(n / 2)
11 iter = head
12 while (mid--) {
13 iter = iter.next
14 }
15
16 return iter
17}

Approach: Fast and Slow

Slow pointer go 1 step, in the same time fast pointer go 2 steps

Implementation

1var middleNode = function (head) {
2 for (var slow = (fast = head); fast && fast.next; ) {
3 slow = slow.next
4 fast = fast.next.next
5 }
6
7 return slow
8}

Comments

Loading comments...

Tags

leetcode

linked list

two pointers

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Permutation in String

Notice the constraints

HoningJS

Search Posts