You are 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.
[1, 100].int value and a next reference to the next node in the list, or null if it is the last node.Here is the code to find the middle of the linked list:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def middleNode(head: ListNode) -> ListNode:
slow = fast = head
# Traverse the list with two pointers at different speeds
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
The strategy to solve this problem uses the Two Pointers approach:
slow and fast, both pointing to the start of the linked list.slow pointer one step at a time.fast pointer two steps at a time.fast pointer reaches the end of the list, the slow pointer will be at the middle of the list.fast pointer moves twice as fast as the slow pointer, so when fast reaches the end, slow will have covered half the distance.slow will already be at the middle (and start).slow will end up at the second middle node when fast reaches the end.The time complexity of this approach is O(n), where n is the number of nodes in the linked list.
slow and fast pointers traverse the list, but since fast moves twice as fast, the loop will terminate after n/2 iterations, which is still O(n).The space complexity is O(1) because we are using only a fixed amount of extra space (i.e., the two pointers).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?