Skip to content

Latest commit

 

History

History

876-MiddleoftheLinkedList

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

Middle of the Linked List

Problem can be found in here!

# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

Solution: Fast and Slow Pointers

def middleNode(head: Optional[ListNode]) -> Optional[ListNode]:
    fast_pointer = slow_pointer = head

    while fast_pointer and fast_pointer.next:
        fast_pointer = fast_pointer.next.next
        slow_pointer = slow_pointer.next

    return slow_pointer

Time Complexity: O(n), Space Complexity: O(1)