Add one to a number represented as linked list | Set 2 - GeeksforGeeks

06 Jul, 2021
Given a singly linked list which represents a number where each node contains only one digit [0 – 9]. The task is to add 1 to the number represented by the given linked list and print the new linked list.Examples: 
Input: 1 -> 2 -> 9 -> 9 -> NULL Output: Original list is : 1 2 9 9 Resultant list is : 1 3 0 0
Input: 9 -> 9 -> 9 -> 9 -> NULL Output: Original list is : 9 9 9 9 Resultant list is : 1 0 0 0 0 
Approach: A previous implementation of the above problem was discussed in this post. However, one of the implementations requires the linked list to be reversed and the other makes use of recursion. An O(1) space complexity solution is been discussed here which doesn’t require the linked list to be reversed. The main focus in this question is on the digit 9 which creates all the changes otherwise for other digits we have to just increment their value by 1 but if we change the node’s value with the value 9 it makes a carry which then has to be passed through the linked list.Find the last node in the linked list which is not equal to 9. Now there are three cases: 
If there is no such node i.e. the value of every node is 9 then the new linked list will contain all 0s and a single 1 inserted at the head of the linked list.If the rightmost node which is not equal to 9 is the last node in the linked list then add 1 to this node and return the head of the linked list.If the node is other than the last node i.e. every node after it is equal to 9 then add 1 to the current node and change all the nodes after it to 0.
If there is no such node i.e. the value of every node is 9 then the new linked list will contain all 0s and a single 1 inserted at the head of the linked list.
If the rightmost node which is not equal to 9 is the last node in the linked list then add 1 to this node and return the head of the linked list.
If the node is other than the last node i.e. every node after it is equal to 9 then add 1 to the current node and change all the nodes after it to 0.
Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Node of the linked liststruct Node {    int data;    Node* next;}; // Function to create a new nodeNode* create_Node(int data){    Node* temp = new Node();    temp->data = data;    temp->next = NULL;    return temp;} // Function to print the linked listvoid print(Node* head){     Node* temp = head;    while (temp != NULL) {        cout << temp->data << " ";        temp = temp->next;    }    cout << endl;} // Function to add one to a number// represented as linked listNode* addOne(Node* head){     // To store the last node in the linked    // list which is not equal to 9    Node* last = NULL;    Node* cur = head;     // Iterate till the last node    while (cur->next != NULL) {         if (cur->data != 9) {            last = cur;        }        cur = cur->next;    }     // If last node is not equal to 9    // add 1 to it and return the head    if (cur->data != 9) {        cur->data++;        return head;    }     // If list is of the type 9 -> 9 -> 9 ...    if (last == NULL) {        last = new Node();        last->data = 0;        last->next = head;        head = last;    }     // For cases when the rightmost node which    // is not equal to 9 is not the last    // node in the linked list    last->data++;    last = last->next;     while (last != NULL) {        last->data = 0;        last = last->next;    }     return head;} // Driver codeint main(){    Node* head = create_Node(1);    head->next = create_Node(2);    head->next->next = create_Node(9);    head->next->next->next = create_Node(9);     cout << "Original list is : ";    print(head);     head = addOne(head);     cout << "Resultant list is : ";    print(head);     return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ // Node of the linked liststatic class Node{    int data;    Node next;}; // Function to create a new nodestatic Node create_Node(int data){    Node temp = new Node();    temp.data = data;    temp.next = null;    return temp;} // Function to print the linked liststatic void print(Node head){    Node temp = head;    while (temp != null)    {        System.out.print(temp.data + " ");        temp = temp.next;    }    System.out.println();} // Function to add one to a number// represented as linked liststatic Node addOne(Node head){     // To store the last node in the linked    // list which is not equal to 9    Node last = null;    Node cur = head;     // Iterate till the last node    while (cur.next != null)    {        if (cur.data != 9)        {            last = cur;        }        cur = cur.next;    }     // If last node is not equal to 9    // add 1 to it and return the head    if (cur.data != 9)    {        cur.data++;        return head;    }     // If list is of the type 9 . 9 . 9 ...    if (last == null)    {        last = new Node();        last.data = 0;        last.next = head;        head = last;    }     // For cases when the rightmost node which    // is not equal to 9 is not the last    // node in the linked list    last.data++;    last = last.next;     while (last != null)    {        last.data = 0;        last = last.next;    }    return head;} // Driver codepublic static void main(String[] args){    Node head = create_Node(1);    head.next = create_Node(2);    head.next.next = create_Node(9);    head.next.next.next = create_Node(9);     System.out.print("Original list is : ");    print(head);     head = addOne(head);     System.out.print("Resultant list is : ");    print(head);}} // This code is contributed// by PrinciRaj1992
# A Python3 implementation of the approach # Node of the linked listclass Node():    def __init__(self):        self.data = None        self.next = None # Function to create a new nodedef create_Node(data):    temp = Node()    temp.data = data    temp.next = None    return temp # Function to print the linked listdef printList(head):    temp = head    while (temp != None):        print(temp.data, end = ' ')        temp = temp.next    print() # Function to add one to a number# represented as linked listdef addOne(head):     # To store the last node in the    # linked list which is not equal to 9    last = None    cur = head     # Iterate till the last node    while(cur.next != None):        if(cur.data != 9):            last = cur        cur = cur.next     # If last node is not equal to 9    # add 1 to it and return the head    if(cur.data != 9):        cur.data += 1        return head     # If list is of the type 9 -> 9 -> 9 ...    if(last == None):        last = Node()        last.data = 0        last.next = head        head = last     # For cases when the rightmost node which    # is not equal to 9 is not the last    # node in the linked list    last.data += 1    last = last.next     while(last != None):        last.data = 0        last = last.next     return head # Driver codeif __name__=='__main__':    head = create_Node(1)    head.next = create_Node(2)    head.next.next = create_Node(9)    head.next.next.next = create_Node(9)     print("Original list is : ", end = "")    printList(head)     head = addOne(head)     print("Resultant list is : ", end = "")    printList(head) # This code is contributed by Yashyasvi Agarwal
// C# implementation of the approachusing System;     class GFG{ // Node of the linked listpublic class Node{    public int data;    public Node next;}; // Function to create a new nodestatic Node create_Node(int data){    Node temp = new Node();    temp.data = data;    temp.next = null;    return temp;} // Function to print the linked liststatic void print(Node head){    Node temp = head;    while (temp != null)    {        Console.Write(temp.data + " ");        temp = temp.next;    }    Console.WriteLine();} // Function to add one to a number// represented as linked liststatic Node addOne(Node head){     // To store the last node in the linked    // list which is not equal to 9    Node last = null;    Node cur = head;     // Iterate till the last node    while (cur.next != null)    {        if (cur.data != 9)        {            last = cur;        }        cur = cur.next;    }     // If last node is not equal to 9    // add 1 to it and return the head    if (cur.data != 9)    {        cur.data++;        return head;    }     // If list is of the type 9 . 9 . 9 ...    if (last == null)    {        last = new Node();        last.data = 0;        last.next = head;        head = last;    }     // For cases when the rightmost node which    // is not equal to 9 is not the last    // node in the linked list    last.data++;    last = last.next;     while (last != null)    {        last.data = 0;        last = last.next;    }    return head;} // Driver codepublic static void Main(String[] args){    Node head = create_Node(1);    head.next = create_Node(2);    head.next.next = create_Node(9);    head.next.next.next = create_Node(9);     Console.Write("Original list is : ");    print(head);     head = addOne(head);     Console.Write("Resultant list is : ");    print(head);}} // This code is contributed by 29AjayKumar
<script>     // Javascript implementation of the approach // Node of the linked listclass Node {     constructor()    {        this.data =0;        this.next = null;    }}; // Function to create a new nodefunction create_Node(data){    var temp = new Node();    temp.data = data;    temp.next = null;    return temp;} // Function to print the linked listfunction print(head){     var temp = head;    while (temp != null) {        document.write( temp.data + " ");        temp = temp.next;    }    document.write("<br>");} // Function to add one to a number// represented as linked listfunction addOne(head){     // To store the last node in the linked    // list which is not equal to 9    var last = null;    var cur = head;     // Iterate till the last node    while (cur.next != null) {         if (cur.data != 9) {            last = cur;        }        cur = cur.next;    }     // If last node is not equal to 9    // add 1 to it and return the head    if (cur.data != 9) {        cur.data++;        return head;    }     // If list is of the type 9 . 9 . 9 ...    if (last == null) {        last = new Node();        last.data = 0;        last.next = head;        head = last;    }     // For cases when the rightmost node which    // is not equal to 9 is not the last    // node in the linked list    last.data++;    last = last.next;     while (last != null) {        last.data = 0;        last = last.next;    }     return head;} // Driver codevar head = create_Node(1);head.next = create_Node(2);head.next.next = create_Node(9);head.next.next.next = create_Node(9);document.write( "Original list is : ");print(head);head = addOne(head);document.write( "Resultant list is : ");print(head); // This code is contributed by rrrtnx.</script>
Original list is : 1 2 9 9 
Resultant list is : 1 3 0 0
 
Time Complexity: O(N)
Space Complexity: O(1)
princiraj1992
29AjayKumar
yashyasviagarwal
shrey25
user_ztnc
rrrtnx
sooda367
Linked List
Recursion
Linked List
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Circular Linked List | Set 2 (Traversal)
Swap nodes in a linked list without swapping data
Program to implement Singly Linked List in C++ using class
Circular Singly Linked List | Insertion
Given a linked list which is sorted, how will you insert in sorted way
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Recursion
Program for Tower of Hanoi
Backtracking | Introduction