This problem asks to increment a number represented as a linked list by one. The solution uses a single pass through the linked list to find the rightmost non-9 digit, increment it, and then set all subsequent digits to 0.
Algorithm:
Create a Dummy Node: A dummy node is prepended to the linked list. This simplifies handling the case where the entire linked list consists of 9s (resulting in a carry-over to a new leading 1).
Find the Rightmost Non-9 Digit: The algorithm iterates through the linked list, keeping track of the rightmost node whose value is not 9. This node (target
) is where the increment will take place.
Increment and Zero Out: The value of the target
node is incremented by 1. Then, the algorithm iterates from the node after target
to the end of the list, setting the value of each node to 0.
Handle Carry-over: If the dummy node's value is 1 (meaning there was a carry-over from the most significant digit), the dummy node is returned; otherwise, the node after the dummy node (the original head) is returned.
Time Complexity: O(N), where N is the number of nodes in the linked list. The algorithm performs a single traversal of the list.
Space Complexity: O(1). The algorithm uses a constant amount of extra space, regardless of the size of the linked list. The dummy node is a constant space overhead.
Code Explanation (Python):
class Solution:
def plusOne(self, head: ListNode) -> ListNode:
dummy = ListNode(0, head) # Create dummy node
target = dummy # Initialize target to the dummy node
while head: # Iterate through the list
if head.val != 9:
target = head # Update target if a non-9 digit is found
head = head.next # Move to the next node
target.val += 1 # Increment the target node's value
target = target.next # Move to the next node after the target
while target: # Set subsequent nodes to 0
target.val = 0
target = target.next
return dummy if dummy.val else dummy.next # Return dummy if carry-over, otherwise return head
The Java, C++, and Go solutions follow the same logic and have the same time and space complexity. They only differ in syntax. The core idea of using a dummy node, finding the rightmost non-9 digit, incrementing it, zeroing out subsequent digits, and handling the carry-over remains consistent across all implementations.