Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created June 29, 2023 20:54
Show Gist options
  • Save Ifihan/d3707242b8d3609ea1a1ef8107f2b3a7 to your computer and use it in GitHub Desktop.
Save Ifihan/d3707242b8d3609ea1a1ef8107f2b3a7 to your computer and use it in GitHub Desktop.
Middle of the Linked List

Middle of the Linked List

Question on Leetcode - Easy

Approach

The approach I took was to use two pointers. One moved the normal speed, while the other went twice as fast as the first pointer.

When the faster pointer reaches the end, it returns the value (node) of the value at that time.

Code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
        slow = head
        fast = head
        while fast is not None and fast.next is not None:
            slow = slow.next
            fast = fast.next.next
        return slow

Complexities

  • Time complexity: O(n)
  • Space complexity: O(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment