VOOZH about

URL: https://www.geeksforgeeks.org/dsa/add-1-number-represented-linked-list/

⇱ Add 1 to a number represented as linked list - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Add 1 to a number represented as linked list

Last Updated : 3 Apr, 2026

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 -> 6
Output: head: 4 -> 5 -> 7
Explanation: Adding 1 to number represented by Linked List = 456 + 1 = 457

👁 Image

Input: head: 2 -> 1 -> 6 -> 9
Output: head: 2 -> 1 -> 7 -> 0
Explanation: Adding 1 to number represented by Linked List = 2169 + 1 = 2170

Recursive - O(n) Time and O(n) Space:

  • Recursively traverse the linked list, reaching the last node first. This ensures that the least significant digit is processed before others.
  • Add 1 to the value of the last node and compute any carry resulting from this addition.
  • While backtracking, update each node's value based on the carry propagated from the subsequent node.
  • After traversing, if the carry is not equals to 0, create new node with the data as carry and insert it at head.

Output
2 0 0 0 

Time Complexity: O(n), where n is the number of nodes in the linked list.
Auxiliary Space: O(n)

Iterative - O(n) Time and O(1) Space:

  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. This gives us 0->0->0->2
  3. After traversing, if the carry is not equals to 0, create new node with the data as carry and insert it at head. In this case, the carry is 0.
  4. Reverse modified linked list and return head. This gives us 2->0->0->0

Output
2 0 0 0 

Time Complexity: O(n), where n is the number of nodes in the linked list.
Auxiliary Space: O(1), As constant extra space is used.


Comment
Article Tags: