LeetCode #876: Middle of the Linked List
β’ 121 words β’ 1 min β’ updated
LeetCode #876: Middle of the Linked List:
python
# 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]:
if not head:
return head
if not head.next:
return head
if not head.next.next:
return head.next
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slowThis works too:
python
# 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 and fast.next:
slow = slow.next
fast = fast.next.next
return slow