LeetCode: Middle of the Linked List Solution
Several waysApproach: Calculate Length
Calculate list length
Iterate to the middle
Implementation
1var middleNode = function (head) {2 let n = 034 let iter = head5 while (iter) {6 n++7 iter = iter.next8 }910 let mid = Math.floor(n / 2)11 iter = head12 while (mid--) {13 iter = iter.next14 }1516 return iter17}
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.next4 fast = fast.next.next5 }67 return slow8}
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.