FastPrepMiddle of a Linked List

Middle of a Linked List

Apple logoApple● EasyNEW GRADONSITE INTERVIEW
Learn

Problem statement

Return the middle node of a singly linked list. If its length is even, return the second of its two middle nodes. Return null for an empty list, and do not change any next pointer.

Lists are displayed as their node-value sequences. The returned node is displayed as the suffix beginning at that node; an empty sequence represents null.

Function

middleNode(head: ListNode) → ListNode

Examples

Example 1

head = [1,2,3,4,5]return = [3,4,5]

The third node is the middle of five nodes.

Example 2

head = [1,2,3,4,5,6]return = [4,5,6]

The fourth node is the second middle of six nodes.

Example 3

head = []return = []

An empty list has no middle node.

Constraints

  • The list is acyclic and contains between 0 and 10^5 nodes.
  • -10^9 <= node.val <= 10^9.

More Apple problems

See Apple hiring insights
public ListNode middleNode(ListNode head) {
    // Write your solution here.
}
head[1,2,3,4,5]
expected[3,4,5]
Checking account…