876. Middle of the Linked List
LeetCode Solution: Find the Middle of a Linked List in JavaScript
Finding the middle node of a singly-linked list is a common problem on LeetCode. In this post, we will walk through the intuition, approach, and complexity of solving this problem using JavaScript. Below is the complete code solution, along with an explanation.
Intuition
To find the middle node of a linked list efficiently, we can use the two-pointer technique. By using two pointers, slow
and fast
, where slow
moves one step at a time and fast
moves two steps at a time, we can ensure that when fast
reaches the end of the list, slow
will be at the middle. This method allows us to determine the middle node in a single pass through the list.
Approach
Initialize Two Pointers:
Initialize
slow
andfast
pointers to the head of the linked list.
Traverse the List:
Use a
while
loop to moveslow
one step at a time andfast
two steps at a time.Continue the loop until
fast
reaches the end of the list orfast.next
isnull
.
Return the Middle Node:
When the loop exits,
slow
will be at the middle node of the list.Return the
slow
pointer.
Code
Here’s the complete JavaScript code for finding the middle node of a singly-linked list:
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var middleNode = function(head) {
let slow = head;
let fast = head;
while(fast && fast.next) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
};
Complexity
Time Complexity: O(n), where
n
is the number of nodes in the linked list. The function makes a single pass through the list.Space Complexity: O(1), as we are using a constant amount of extra space for the
slow
andfast
pointers.
Example
Here’s how you can use this function:
// Define the ListNode class
function ListNode(val, next) {
this.val = (val === undefined ? 0 : val);
this.next = (next === undefined ? null : next);
}
// Create a linked list: 1 -> 2 -> 3 -> 4 -> 5
let head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
// Find the middle node
let middle = middleNode(head);
console.log(middle.val); // Output: 3
Conclusion
This approach provides an efficient and straightforward solution to finding the middle node of a singly-linked list. By using the two-pointer technique, we can determine the middle node in linear time with constant space complexity.
For more detailed explanations and additional solutions, check out my solution on LeetCode: Middle of the Linked List - LeetCode
I hope this guide helps you understand how to solve the problem of finding the middle node in a linked list using JavaScript. Happy coding! š
If you have any questions or need further clarification, feel free to ask in the comments below!
Comments
Post a Comment