[
linked list
two pointers
]
Leetcode 0876 Middle of the Linked List
Problem statement
https://leetcode.com/problems/middle-of-the-linked-list/
Solution
Use two pointers: slow and fast, when fast will reach the end, slow one will be in the middle of list.
Complexity
Time complexity is O(n) ~ 1.5n
, space complexity is O(1)
.
Code
class Solution:
def middleNode(self, head):
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow