#750Medium· asked at 1 company
Insertion at the tail of Linked List
Problem
Given the head of a singly linked list and an integer val, append a new node with value val at the end of the list and return the head. If the list is empty, the new node becomes the head.
Input / Output
- Input: head (possibly
null), integerval. - Output: head of the updated list.
Examples
Example 1
Input: 1 -> 2 -> 3, val = 4
Output: 1 -> 2 -> 3 -> 4
Example 2
Input: empty, val = 9
Output: 9
Constraints
0 <= number of nodes <= 10^5
Approach
- If
headisnull, return a new node. - Walk
curuntilcur.nextisnull(the last node). - Set
cur.next = ListNode(val)and returnhead.
Appending costs O(n) because a singly linked list has no direct reference to its last node. In practice, list implementations keep a tail pointer so that append becomes O(1) — a good point to raise. With a tail pointer: tail.next = node; tail = node.
Follow-up: append k values in one pass by keeping cur at the tail after the first append rather than re-walking each time.
Complexity
- Time: O(n) (O(1) with a tail pointer)
- Space: O(1)
Reference solution (Python)
def insert_tail(head, val):
node = ListNode(val)
if head is None:
return node
cur = head
while cur.next:
cur = cur.next
cur.next = node
return head
Test cases
| Input | Expected |
|---|---|
1->2->3, val=4 | [1,2,3,4] |
empty, val=9 | [9] |
7, val=8 | [7,8] |
| append twice to empty (1 then 2) | [1,2] |