Plus One Linked List

Updated on 01 July, 2025
Plus One Linked List header image

Problem Statement

The task requires us to handle a non-negative integer which is represented by a linked list of digits where the most significant digit is at the head of the list. This sequence needs to be incremented by one. Given the linear nature of a linked list, accessing digits from the least significant end (commonly needed for addition operations due to carries) is not straightforward. Moreover, since digits are stored in individual nodes, handling overflows that lead to new nodes being added (for example, turning 999 into 1000) needs careful consideration.

Examples

Example 1

Input:

head = [1,2,3]

Output:

[1,2,4]

Example 2

Input:

head = [0]

Output:

[1]

Constraints

  • The number of nodes in the linked list is in the range [1, 100].
  • 0 <= Node.val <= 9
  • The number represented by the linked list does not contain leading zeros except for the zero itself.

Approach and Intuition

Before diving into the code implementation, it's crucial to understand the intuition and approach behind solving the problem of adding one to a number represented by a linked list. Here's a step-by-step breakdown:

  1. Handling carries:

    • Since the least significant digit is at the end of the list and there's no direct backtracking in a singly linked list, one efficient way is to reverse the linked list. This allows us to add 1 starting from the least significant digit and easily manage carry-overs.
  2. Reversing the linked list:

    • To begin, reverse the given linked list so that the least significant digit comes to the head. This typical operation can be achieved using iterative pointer manipulation.
  3. Adding one:

    • Start from the head of the reversed linked list, add one to the digit and manage the carry as you move to next digits. If a carry is leftover once the end of the list is reached, a new node has to be created and added.
  4. Reverse again to restore original order:

    • As the operation of adding 1 might have altered the order of elements to facilitate easier calculation, ensure to reverse the linked list again to restore the original most significant digit at the head.

By executing these steps, we utilize the linked list property effectively while manipulating the list minimally to achieve the desired outcome.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    ListNode* increment(ListNode* head) {
        ListNode* dummy = new ListNode(0);
        dummy->next = head;
        ListNode* lastNonNine = dummy;
    
        while (head != nullptr) {
            if (head->val != 9) lastNonNine = head;
            head = head->next;
        }
            
        lastNonNine->val++;
        lastNonNine = lastNonNine->next;
    
        while (lastNonNine != nullptr) {
            lastNonNine->val = 0;
            lastNonNine = lastNonNine->next;
        }
    
        delete lastNonNine;
        return dummy->val != 0 ? dummy : dummy->next;
    }
};

The "Plus One Linked List" problem involves incrementing the number represented by a linked list by one. Each node in the linked list contains a single digit, and the digits are stored in reverse order.

In the CPP solution provided:

  • Initialize a dummy node for easier manipulation of edge cases, and set a pointer (lastNonNine) to this dummy node.
  • Traverse the linked list to update the lastNonNine pointer to the last node before encountering a node with the value 9.
  • Increment the value of lastNonNine by one.
  • Then, traverse from the node next to lastNonNine, setting all subsequent nodes' values to 0 (because they were 9s that overflowed).
  • A node deletion occurs to clean up.
  • Finally, return the adjusted list. If the dummy node’s value remains zero, it implies no carry affected the first node and it returns the list starting from the original head. Otherwise, it returns the dummy node to accommodate cases where there is a carry that affects every digit (e.g., 999 + 1).

Ensure safe memory management to avoid leaks, and follow a cautious approach while manipulating linked list nodes to preserve data integrity.

java
class Solution {
    public ListNode incrementLast(ListNode head) {
        // Create a dummy node
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode lastNotNine = dummy;
    
        // Traverse to the last non-nine node
        while (head != null) {
            if (head.val != 9) {
                lastNotNine = head;
            }
            head = head.next;
        }
    
        // Increment the value of the last non-nine node
        lastNotNine.val++;
        lastNotNine = lastNotNine.next;
    
        // Turn all following nine nodes to zero
        while (lastNotNine != null) {
            lastNotNine.val = 0;
            lastNotNine = lastNotNine.next;
        }
    
        return dummy.val != 0 ? dummy : dummy.next;
    }
}

The "Plus One Linked List" problem in Java increments the number represented by a singly linked list by one. Each node classically represents one digit, with the head being the least significant digit. This solution creates a workable method to add one to the number represented by the list and handles all the cases, including carries effectively.

Here's the detailed breakdown:

  1. Initialize a dummy node pointing to the head of the list. This dummy helps in case of a carry out from the most significant digit.
  2. Use a pointer to traverse through the list and locate the last node before a sequence of nines, as only this segment needs attention for increment and potential cascading changes.
  3. Increment the value of this last non-nine node.
  4. Set all subsequent nodes (which contain the digit nine) to zero, as these get affected by the carry.
  5. Check if there's a carry out from the most significant digit by assessing whether the dummy node’s value is zero. If it's non-zero, return the dummy node; otherwise, return dummy.next to skip the dummy and continue with the rest of the list.

This solution efficiently processes adding one to the represented number without having to reverse the list or convert it to another data structure, managing both space and complexity constraints. The edge cases, particularly when the entire list consists of nines, are handled gracefully, avoiding the common pitfalls of linked list manipulations with a simple and direct approach.

python
class Solution:
    def incrementByOne(self, start: ListNode) -> ListNode:
        dummy = ListNode(0)
        dummy.next = start
        non_nine = dummy
    
        # Traverse to find the rightmost non-nine
        while start:
            if start.val != 9:
                non_nine = start
            start = start.next
    
        # Increment the identified position
        non_nine.val += 1
        non_nine = non_nine.next
    
        # Reset all subsequent nines to zero
        while non_nine:
            non_nine.val = 0
            non_nine = non_nine.next
    
        return dummy if dummy.val else dummy.next

The provided Python3 code defines a class Solution with a method incrementByOne to add one to a number represented as a linked list. This method transforms the number by navigating through each node of the linked list, scanning for the rightmost non-nine digit to handle scenarios where overflow occurs after addition.

In more detail:

  • It initializes a dummy node that points to the starting node of the linked list.
  • It identifies the rightmost node whose value is not 9, to manage potential carry in the addition.
  • After the increment operation, any node that originally contained the digit 9 and follows a changed node (that caused a carry) is reset to 0.
  • Depending on whether the dummy's value has changed to 1 due to a carry affecting the most significant digit, it returns either the modified linked list starting at the dummy node or the linked list starting after the dummy node.

A typical scenario where this code is beneficial is when you need to add one to a number represented in reverse order in a linked list, such as representing 129 as the linked list 9->2->1. This code helps manage additions that result in a carry, particularly when all digits in the segments are nines, thus simplifying what would otherwise be a more complex manipulation of linked list nodes.

Comments

No comments yet.