Subtract 1 from a number represented as Linked List

• Difficulty Level : Medium
• Last Updated : 22 Jun, 2021

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 -> 4
Output: 1 -> 2 -> 3 -> 3

Input: LL = 1 -> 2
Output: 1 -> 1

Approach: The given problem can be solved by using recursion. Follow the steps below to solve the problem:

• Define a function, say subtractOneUtil(Node *head) that takes the head of the linked list as the arguments and perform the following steps:
• Base Case: If the head node of the Linked List is NULL, then return -1 from that recursive call.
• Recursive Call: Recursively call for the next node of the linked list and let the value returned by this recursive call be borrow.
• If the value of borrow is -1 and the value of the head node is 0, then update the value of the head node to 9 and return -1 from the current recursive call.
• Otherwise, decrement the value of the head node by 1 and return 0 from the current recursive call.
• Subtract 1 from the Linked List by calling the above function as subtractOneUtil(head).
• After completing the above steps, print the updated linked list as the resultant linked list.

Below is the implementation of the above approach:

Javascript



Output:

List is 1000
Resultant list is 999

Time Complexity: O(N), N is the length of the given linked list.
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up
Recommended Articles
Page :