nathanwailes

Linked List - Get middle node

Aug 21st, 2024 (edited)
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.88 KB | None | 0 0
  1. """
  2. https://leetcode.com/problems/middle-of-the-linked-list/description/
  3.  
  4. Given the head of a singly linked list, return the middle node of the linked list.
  5.  
  6. If there are two middle nodes, return the second middle node.
  7.  
  8. 2024.08.21 - I think what trips me up about the prompt is the requirement to return the second middle node. It sounds like it'll require some extra logic to handle, when in fact it's just the way things work by default if you use the fast-and-slow-pointer approach.
  9. """
  10.  
  11. # Definition for singly-linked list.
  12. # class ListNode:
  13. #     def __init__(self, val=0, next=None):
  14. #         self.val = val
  15. #         self.next = next
  16. class Solution:
  17.     def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
  18.         slow = fast = head
  19.         while fast and fast.next:
  20.             fast = fast.next.next
  21.             slow = slow.next
  22.         return slow
Advertisement
Add Comment
Please, Sign In to add comment