Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Recursion
  • Practice Recursion
  • MCQs on Recursion
  • Recursion Tutorial
  • Recursive Function
  • Recursion vs Iteration
  • Types of Recursions
  • Tail Recursion
  • Josephus Problem
  • Tower of Hanoi
  • Check Palindrome
Open In App
Next Article:
Add Two Numbers Represented as Linked List
Next article icon

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

Last Updated : 06 Jul, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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: 

  1. 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.
  2. 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.
  3. 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++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std;  // Node of the linked list struct Node {     int data;     Node* next; };  // Function to create a new node Node* create_Node(int data) {     Node* temp = new Node();     temp->data = data;     temp->next = NULL;     return temp; }  // Function to print the linked list void 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 list 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 code int 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
// Java implementation of the approach import java.util.*;  class GFG {  // Node of the linked list static class Node  {     int data;     Node next; };  // Function to create a new node static Node create_Node(int data) {     Node temp = new Node();     temp.data = data;     temp.next = null;     return temp; }  // Function to print the linked list static 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 list static 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 code public 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 
Python3
# A Python3 implementation of the approach  # Node of the linked list class Node():     def __init__(self):         self.data = None         self.next = None  # Function to create a new node def create_Node(data):     temp = Node()     temp.data = data     temp.next = None     return temp  # Function to print the linked list def 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 list def 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 code if __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#
// C# implementation of the approach using System;      class GFG {  // Node of the linked list public class Node  {     public int data;     public Node next; };  // Function to create a new node static Node create_Node(int data) {     Node temp = new Node();     temp.data = data;     temp.next = null;     return temp; }  // Function to print the linked list static 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 list static 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 code public 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 
JavaScript
<script>      // Javascript implementation of the approach  // Node of the linked list class Node {      constructor()     {         this.data =0;         this.next = null;     } };  // Function to create a new node function create_Node(data) {     var temp = new Node();     temp.data = data;     temp.next = null;     return temp; }  // Function to print the linked list function 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 list function 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 code var 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>  

Output: 
Original list is : 1 2 9 9  Resultant list is : 1 3 0 0

 

Time Complexity: O(N)

Space Complexity: O(1)


Next Article
Add Two Numbers Represented as Linked List
author
md1844
Improve
Article Tags :
  • Linked List
  • Recursion
  • DSA
Practice Tags :
  • Linked List
  • Recursion

Similar Reads

  • Add 1 to a number represented as linked list
    A number is represented in linked list such that each digit corresponds to a node in linked list. The task is to add 1 to it. Examples: Input: head: 4 -> 5 -> 6Output: head: 4 -> 5 -> 7Explanation: Adding 1 to number represented by Linked List = 456 + 1 = 457 Input: head: 2 -> 1 ->
    15+ min read
  • Add Two Numbers Represented as Linked List
    Given two numbers represented as two lists, the task is to return the sum of two lists. Note: There can be leading zeros in the input lists, but there should not be any leading zeros in the output list. Examples: Input: num1 = 4 -> 5, num2 = 3 -> 4 -> 5Output: 3 -> 9 -> 0 Explanation:
    15+ min read
  • Add Two Numbers represented as Linked List using Recursion
    Given two numbers represented as two lists, the task is to return the sum of two lists using recursion. Note: There can be leading zeros in the input lists, but there should not be any leading zeros in the output list. Examples: Input: num1 = 4 -> 5, num2 = 3 -> 4 -> 5Output: 3 -> 9 -
    14 min read
  • Subtract 1 from a number represented as Linked List
    Given the head of the linked list representing a positive integer, the task is to print the updated linked list after subtracting 1 from it. Examples: Input: LL = 1 -> 2 -> 3 -> 4Output: 1 -> 2 -> 3 -> 3 Input: LL = 1 -> 2Output: 1 -> 1 Approach: The given problem can be solv
    15+ min read
  • Subtract Two Numbers represented as Linked Lists
    Given two linked lists that represent two large positive numbers. Subtract the smaller number from the larger one and return the difference as a linked list. Note that the input lists may be in any order, but we always need to subtract smaller ones from larger ones.Note: It may be assumed that there
    15+ min read
  • Add number and its reverse represented by Linked List
    Given a number represented by a linked list, write a function that returns the sum of that number with its reverse form, and returns the resultant linked list. Note: Avoid modifying the original linked list. Examples: Input: 1->2->3->4 Output: 5->5->5->5Explanation: Input list: 1 2
    12 min read
  • Double a Number Represented in a Linked List
    Given a non-empty linked list representing a non-negative integer without leading zeroes the task is to double the value of whole linked list like(2->3->1 then answer will be 4->6->2) and print the resultant linked list. Examples: Input: head = [2, 0, 9]Output: [4, 1, 8]Explanation: Give
    9 min read
  • Javascript Program For Adding 1 To A Number Represented As Linked List
    Number is represented in linked list such that each digit corresponds to a node in linked list. Add 1 to it. For example 1999 is represented as (1-> 9-> 9 -> 9) and adding 1 to it should change it to (2->0->0->0) Below are the steps : Reverse given linked list. For example, 1->
    5 min read
  • Add two numbers represented by Linked List without any extra space
    Given two numbers represented by two linked lists, write a function that returns sum list. The sum list is linked list representation of addition of two input numbers. Expected Space Complexity O(1). Examples: Input: L1 = 5 -> 6 -> 3 -> NULL L2 = 8 -> 4 -> 2 -> NULL Output: 1 ->
    11 min read
  • Javascript Program To Subtract Two Numbers Represented As Linked Lists
    Given two linked lists that represent two large positive numbers. Subtract the smaller number from the larger one and return the difference as a linked list. Note that the input lists may be in any order, but we always need to subtract smaller from the larger ones.It may be assumed that there are no
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences