Post

Leetcode 0876. Middle of the Linked List

Given the `head` of a singly linked list, return _the middle node of the linked list_. If there are two middle nodes, return the second middle node.                                                                                                     

Description

Given the head of a singly linked list, return the middle node of the linked list.

If there are two middle nodes, return the second middle node.

Example 1:

Input: head = [1,2,3,4,5]
Output: [3,4,5]
  • The middle node of the list is node 3.

Binary Tree Preorder Traversal

Example 2:

Input: head = [1,2,3,4,5,6]
Output: [4,5,6]
  • Since the list has two middle nodes with values 3 and 4, we return the second one.

Binary Tree Preorder Traversal

Constraints:

  • The number of nodes in the list is in the range [1, 100].
  • 1 <= Node.val <= 100

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    # Iteration
    # Time Complexity: BigO(N)
    # Space Complexity: BigO(N)
    def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
        hare = head
        tortoise = head
        while hare and hare.next:
            hare = hare.next.next
            tortoise = tortoise.next

        return tortoise
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
 * Definition for singly-linked list.
 */
class ListNode {
  val: number;
  next: ListNode | null;
  constructor(val?: number, next?: ListNode | null) {
    this.val = val === undefined ? 0 : val;
    this.next = next === undefined ? null : next;
  }
}

/**
 * Iteration
 * Time Complexity: BigO(N)
 * Space Complexity: BigO(N)
 */
function middleNode(head: ListNode | null): ListNode | null {
  let hare = head;
  let tortoise = head;
  while (hare && hare.next) {
    hare = hare.next?.next;
    tortoise = tortoise.next;
  }
  return tortoise;
}
This post is licensed under CC BY 4.0 by the author.