Intermediate · easy · linked-list, two-pointers
Middle of the Linked List
El reto
El enunciado va en inglés, igual que en el vídeo.
Given the head of a singly linked list, return its middle node, walking the list only once. If the list has an even number of nodes there are two middle nodes: return the second one.
Example
1 -> 2 -> 3 -> 4 -> 5 -> 3
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 4Idea: two pointers start at the head. The slow one moves one node per step and the fast one moves two, so when the fast one reaches the end, the slow one has covered exactly half of the list. Stop when fast or fast.next is null; with an even length that leaves slow on the second middle node. Time O(n), space O(1), and no need to count the nodes first. The same two pointers find a cycle in a list (Floyd's algorithm).
La solución
# Middle of the Linked List - ayotl.dev
class Node:
def __init__(self, val, next=None):
self.val, self.next = val, next
def middle(head):
slow = fast = head
# fast moves 2, slow moves 1: when
# fast reaches the end, slow is halfway
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
for n in (5, 6):
head = None # the list 1 -> ... -> n
for v in range(n, 0, -1):
head = Node(v, head)
print(f"1..{n} ->", middle(head).val)
$ python3 middle_of_the_linked_list.py
1..5 -> 3
1..6 -> 4