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
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Program To Add Two Numbers Represented By Linked Lists- Set 1
Next article icon

Python Program For Adding 1 To A Number Represented As Linked List

Last Updated : 29 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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) 

Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.

Below are the steps : 

  1. Reverse given linked list. For example, 1-> 9-> 9 -> 9 is converted to 9-> 9 -> 9 ->1.
  2. Start traversing linked list from leftmost node and add 1 to it. If there is a carry, move to the next node. Keep moving to the next node while there is a carry.
  3. Reverse modified linked list and return head.

Below is the implementation of above steps. 

Python3




# Python3 program to add 1 to
# a linked list
import sys
import math
 
# Linked list node
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
 
# Function to create a new node
# with given data
def newNode(data):
    return Node(data)
 
# Function to reverse the
# linked list
def reverseList(head):
    if not head:
        return
    curNode = head
    prevNode = head
    nextNode = head.next
    curNode.next = None
 
    while(nextNode):
        curNode = nextNode
        nextNode = nextNode.next
        curNode.next = prevNode
        prevNode = curNode
 
    return curNode
 
# Adds one to a linked lists and
# return the head node of
# resultant list
def addOne(head):
 
    # Reverse linked list and add
    # one to head
    head = reverseList(head)
    k = head
    carry = 0
    prev = None
    head.data += 1
 
    # update carry for next calculation
    while(head != None) and (head.data > 9 or carry > 0):
        prev = head
        head.data += carry
        carry = head.data // 10
        head.data = head.data % 10
        head = head.next
 
    if carry > 0:
        prev.next = Node(carry)
    # Reverse the modified list
    return reverseList(k)
 
# A utility function to print
# a linked list
def printList(head):
    if not head:
        return
 
    while(head):
        print("{}".format(head.data), end="")
        head = head.next
 
# Driver code
if __name__ == '__main__':
    head = newNode(1)
    head.next = newNode(9)
    head.next.next = newNode(9)
    head.next.next.next = newNode(9)
 
    print("List is: ",
           end = "")
    printList(head)
 
    head = addOne(head)
 
    print("Resultant list is: ",
           end = "")
    printList(head)
# This code is contributed by Rohit
 
 

Output:

List is 1999 Resultant list is 2000

Time complexity: O(n)
Auxiliary Space: O(1)

Recursive Implementation: 
We can recursively reach the last node and forward carry to previous nodes. Recursive solution doesn’t require reversing of linked list. We can also use a stack in place of recursion to temporarily hold nodes.

Below is the implementation of recursive solution.

Python




# Recursive Python program to add 1 to
# a linked list
 
# Node class
class Node:
 
    # Constructor to initialize
    # the node object
    def __init__(self, data):
        self.data = data
        self.next = None
 
# Function to create a new node
# with given data
def newNode(data):
 
    new_node = Node(0)
    new_node.data = data
    new_node.next = None
    return new_node
 
# Recursively add 1 from end to beginning
# and returns carry after all nodes are
# processed.
def addWithCarry(head):
 
    # If linked list is empty, then
    # return carry
    if (head == None):
        return 1
 
    # Add carry returned be next node
    # call
    res = head.data + addWithCarry(head.next)
 
    # Update data and return new carry
    head.data = int((res) % 10)
    return int((res) / 10)
 
# This function mainly uses
# addWithCarry().
def addOne(head):
 
    # Add 1 to linked list from end
    # to beginning
    carry = addWithCarry(head)
 
    # If there is carry after processing
    # all nodes, then we need to add a
    # new node to linked list
    if (carry != 0):
     
        newNode = Node(0)
        newNode.data = carry
        newNode.next = head
 
        # New node becomes head now
        return newNode
     
    return head
 
# A utility function to print a
# linked list
def printList(node):
 
    while (node != None):   
        print(node.data,
              end = "")
        node = node.next
     
    print("")
 
# Driver code
head = newNode(1)
head.next = newNode(9)
head.next.next = newNode(9)
head.next.next.next = newNode(9)
 
print("List is ")
printList(head)
 
head = addOne(head)
 
print("Resultant list is ")
printList(head)
# This code is contributed by Arnab Kundu
 
 

Output:

List is 1999 Resultant list is 2000

Time Complexity: O(n)
Auxiliary Space: O(n)

Please refer complete article on Add 1 to a number represented as linked list for more details!



Next Article
Python Program To Add Two Numbers Represented By Linked Lists- Set 1
author
kartik
Improve
Article Tags :
  • DSA
  • Linked List
  • Python Programs
  • Amazon
Practice Tags :
  • Amazon
  • Linked List

Similar Reads

  • Python Program To Add Two Numbers Represented By Linked Lists- Set 1
    Given two numbers represented by two lists, write a function that returns the sum list. The sum list is a list representation of the addition of two input numbers. Example: Input: List1: 5->6->3 // represents number 563 List2: 8->4->2 // represents number 842 Output: Resultant list: 1->4->0->5 // re
    4 min read
  • Python 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
  • Python Program To Multiply Two Numbers Represented By Linked Lists
    Given two numbers represented by linked lists, write a function that returns the multiplication of these two linked lists. Examples: Input: 9->4->6 8->4Output: 79464Input: 3->2->1 1->2Output: 3852Recommended: Please solve it on "PRACTICE" first, before moving on to the solution.Pyt
    3 min read
  • Python Program For Cloning A Linked List With Next And Random Pointer- Set 2
    We have already discussed 2 different ways to clone a linked list. In this post, one more simple method to clone a linked list is discussed. Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. The idea is to use Hashing. Below is algorithm.  Traverse the original link
    3 min read
  • Python Program For Reversing A Doubly Linked List
    Given a Doubly Linked List, the task is to reverse the given Doubly Linked List. See below diagrams for example.  (a) Original Doubly Linked List (b) Reversed Doubly Linked List Here is a simple method for reversing a Doubly Linked List. All we need to do is swap prev and next pointers for all nodes
    4 min read
  • Python Program for Deleting a Node in a Linked List
    We have discussed Linked List Introduction and Linked List Insertion in previous posts on a singly linked list.Let us formulate the problem statement to understand the deletion process. Given a 'key', delete the first occurrence of this key in the linked list. Iterative Method:To delete a node from
    3 min read
  • Python Program For Cloning A Linked List With Next And Random Pointer In O(1) Space
    Given a linked list having two pointers in each node. The first one points to the next node of the list, however, the other pointer is random and can point to any node of the list. Write a program that clones the given list in O(1) space, i.e., without any extra space. Examples: Input : Head of the
    4 min read
  • Python Program For Flattening A Linked List
    Given a linked list where every node represents a linked list and contains two pointers of its type: Pointer to next node in the main list (we call it 'right' pointer in the code below).Pointer to a linked list where this node is headed (we call it the 'down' pointer in the code below). All linked l
    4 min read
  • Python Program For Merge Sort For Doubly Linked List
    Given a doubly linked list, write a function to sort the doubly linked list in increasing order using merge sort.For example, the following doubly linked list should be changed to 24810 Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Merge sort for singly linked l
    3 min read
  • Python Program For Deleting A Node In A Doubly Linked List
    Pre-requisite: Doubly Link List Set 1| Introduction and Insertion Write a function to delete a given node in a doubly-linked list. Original Doubly Linked List  Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Approach: The deletion of a node in a doubly-linked list
    4 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