Given the head of a singly linked list and an integer val, insert a new node with value val at the middle of the list. Return the head of the modified list.
The middle is defined by position. If the list has n nodes, the new node is inserted directly after the node at 0-indexed position n // 2 (integer division). For a list of length 1, that means after the only node. For an empty list, the new node becomes the head.
Function Signature
def insert_at_middle(head: Optional[ListNode], val: int) -> Optional[ListNode]:
Rules
-
A
ListNode
has an integer field
val
and a field
next
that points to the following node, or is
None
at the tail.
-
In the examples a linked list is written as its values from head to tail, and
[]
is the empty list.
-
Let
n
be the number of nodes before the insertion. For a non-empty list, the new node goes immediately after the node at 0-indexed position
n // 2
. For an empty list, return the new node as a one-node list.
-
Insert exactly one node. Every existing node keeps its value and its order relative to the others.
Constraints
-
The number of nodes in the list is between 0 and 10000 inclusive.
-
-10^4 <= Node.val <= 10^4
-
-10^4 <= val <= 10^4
Examples
Input: head = [1,2,3,4,5], val = 99
Output: [1,2,3,99,4,5]
The list has 5 nodes and 5 // 2 = 2, so the new node goes after index 2, which is the node with value 3.
Input: head = [1,2,3,4], val = 50
Output: [1,2,3,50,4]
The list has 4 nodes and 4 // 2 = 2, so the new node again goes after the node with value 3. Only one original node follows it.
Input: head = [8,6], val = 0
Output: [8,6,0]
With 2 nodes, 2 // 2 = 1 is the last node, so the new node is appended at the tail.