Middle of the Linked List:
Given the head
of a singly linked list, return the middle node of the linked list.
If there are two middle nodes, return the second middle node.
Input: head = [1,2,3,4,5]
Output: [3,4,5]
Explanation: The middle node of the list is node 3.
Input: head = [1,2,3,4,5,6]
Output: [4,5,6]
Explanation: Since the list has two middle nodes with values 3 and 4,
we return the second one.
[1, 100]
.1 <= Node.val <= 100
Try this Problem on your own or check similar problems:
public ListNode middleNode(ListNode head) {
ListNode slow = head, fast = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
This is a simple problem easily solved with fast and slow pointers. We have two pointers slow
(moving one step at the time) and fast
(moving two steps at the time). After fast has reached the end of the linked list, the slow one would only have covered
half (actually list.length / 2 would be “index” in the list slow is pointing when fast reached the end which is exactly the middle element). We traverse the list only once leading to linear time complexity.
Don’t settle for anything less than the crown. Join our newsletter and become the King of Interviews! Click here to join now and get the latest updates.