Subtract Two Numbers represented as Linked Lists
Last Updated :
23 Jul, 2025
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 are no extra leading zeros in input lists.
Examples:
Input: l1 = 1 -> 0 -> 0 -> NULL, l2 = 1 -> NULL
Output: 0->9->9->NULL
Explanation: Number represented as
lists are 100 and 1, so 100 - 1 is 099
Input: l1 = 7-> 8 -> 6 -> NULL, l2 = 7 -> 8 -> 9 NULL
Output: 3->NULL
Explanation: Number represented as
lists are 786 and 789, so 789 - 786 is 3,
as the smaller value is subtracted from
the larger one.
- Calculate sizes of given two linked lists.
- If sizes are not the same, then append zeros in the smaller linked list.
- If the size is the same, then follow the below steps:
- Find the smaller valued linked list.
- One by one subtract nodes of the smaller-sized linked list from the larger size. Keep track of borrow while subtracting.
Following is the implementation of the above approach.
C++
// C++ program to subtract smaller valued list from
// larger valued list and return result as a list.
#include <bits/stdc++.h>
using namespace std;
// A linked List Node
struct Node {
int data;
struct Node* next;
};
// A utility which creates Node.
Node* newNode(int data)
{
Node* temp = new Node;
temp->data = data;
temp->next = NULL;
return temp;
}
/* A utility function to get length
of linked list */
int getLength(Node* Node)
{
int size = 0;
while (Node != NULL) {
Node = Node->next;
size++;
}
return size;
}
/* A Utility that padds zeros in front of the
Node, with the given diff */
Node* paddZeros(Node* sNode, int diff)
{
if (sNode == NULL)
return NULL;
Node* zHead = newNode(0);
diff--;
Node* temp = zHead;
while (diff--) {
temp->next = newNode(0);
temp = temp->next;
}
temp->next = sNode;
return zHead;
}
/* Subtract LinkedList Helper is a recursive function,
move till the last Node, and subtract the digits and
create the Node and return the Node. If d1 < d2, we
borrow the number from previous digit. */
Node* subtractLinkedListHelper(Node* l1, Node* l2,
bool& borrow)
{
if (l1 == NULL && l2 == NULL && borrow == 0)
return NULL;
Node* previous = subtractLinkedListHelper(
l1 ? l1->next : NULL, l2 ? l2->next : NULL, borrow);
int d1 = l1->data;
int d2 = l2->data;
int sub = 0;
/* if you have given the value to next digit then
reduce the d1 by 1 */
if (borrow) {
d1--;
borrow = false;
}
/* If d1 < d2, then borrow the number from previous
digit. Add 10 to d1 and set borrow = true; */
if (d1 < d2) {
borrow = true;
d1 = d1 + 10;
}
/* subtract the digits */
sub = d1 - d2;
/* Create a Node with sub value */
Node* current = newNode(sub);
/* Set the Next pointer as Previous */
current->next = previous;
return current;
}
/* This API subtracts two linked lists and returns the
linked list which shall have the subtracted result. */
Node* subtractLinkedList(Node* l1, Node* l2)
{
// Base Case.
if (l1 == NULL && l2 == NULL)
return NULL;
// In either of the case, get the lengths of both
// Linked list.
int len1 = getLength(l1);
int len2 = getLength(l2);
Node *lNode = NULL, *sNode = NULL;
Node* temp1 = l1;
Node* temp2 = l2;
// If lengths differ, calculate the smaller Node
// and padd zeros for smaller Node and ensure both
// larger Node and smaller Node has equal length.
if (len1 != len2) {
lNode = len1 > len2 ? l1 : l2;
sNode = len1 > len2 ? l2 : l1;
sNode = paddZeros(sNode, abs(len1 - len2));
}
else {
// If both list lengths are equal, then calculate
// the larger and smaller list. If 5-6-7 & 5-6-8
// are linked list, then walk through linked list
// at last Node as 7 < 8, larger Node is 5-6-8
// and smaller Node is 5-6-7.
while (l1 && l2) {
if (l1->data != l2->data) {
lNode = l1->data > l2->data ? temp1 : temp2;
sNode = l1->data > l2->data ? temp2 : temp1;
break;
}
l1 = l1->next;
l2 = l2->next;
}
}
// If both lNode and sNode still have NULL value,
// then this means that the value of both of the given
// linked lists is the same and hence we can directly
// return a node with value 0.
if (lNode == NULL && sNode == NULL) {
return newNode(0);
}
// After calculating larger and smaller Node, call
// subtractLinkedListHelper which returns the subtracted
// linked list.
bool borrow = false;
return subtractLinkedListHelper(lNode, sNode, borrow);
}
/* A utility function to print linked list */
void printList(struct Node* Node)
{
while (Node != NULL) {
printf("%d ", Node->data);
Node = Node->next;
}
printf("\n");
}
// Driver program to test above functions
int main()
{
Node* head1 = newNode(1);
head1->next = newNode(0);
head1->next->next = newNode(0);
Node* head2 = newNode(1);
Node* result = subtractLinkedList(head1, head2);
printList(result);
return 0;
}
// This code is contributed by Sania Kumari Gupta (kriSania804)
C
// C program to subtract smaller valued list from
// larger valued list and return result as a list.
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
// A linked List Node
typedef struct Node {
int data;
struct Node* next;
} Node;
// A utility which creates Node.
Node* newNode(int data)
{
Node* temp = (Node*)malloc(sizeof(Node));
temp->data = data;
temp->next = NULL;
return temp;
}
/* A utility function to get length
of linked list */
int getLength(Node* Node)
{
int size = 0;
while (Node != NULL) {
Node = Node->next;
size++;
}
return size;
}
/* A Utility that padds zeros in front of the
Node, with the given diff */
Node* paddZeros(Node* sNode, int diff)
{
if (sNode == NULL)
return NULL;
Node* zHead = newNode(0);
diff--;
Node* temp = zHead;
while (diff--) {
temp->next = newNode(0);
temp = temp->next;
}
temp->next = sNode;
return zHead;
}
/* Subtract LinkedList Helper is a recursive function,
move till the last Node, and subtract the digits and
create the Node and return the Node. If d1 < d2, we
borrow the number from previous digit. */
static bool borrow;
Node* subtractLinkedListHelper(Node* l1, Node* l2)
{
if (l1 == NULL && l2 == NULL && borrow == 0)
return NULL;
Node* previous = subtractLinkedListHelper(
l1 ? l1->next : NULL, l2 ? l2->next : NULL);
int d1 = l1->data;
int d2 = l2->data;
int sub = 0;
/* if you have given the value to next digit then
reduce the d1 by 1 */
if (borrow) {
d1--;
borrow = false;
}
/* If d1 < d2, then borrow the number from previous
digit. Add 10 to d1 and set borrow = true; */
if (d1 < d2) {
borrow = true;
d1 = d1 + 10;
}
/* subtract the digits */
sub = d1 - d2;
/* Create a Node with sub value */
Node* current = newNode(sub);
/* Set the Next pointer as Previous */
current->next = previous;
return current;
}
/* This API subtracts two linked lists and returns the
linked list which shall have the subtracted result. */
Node* subtractLinkedList(Node* l1, Node* l2)
{
// Base Case.
if (l1 == NULL && l2 == NULL)
return NULL;
// In either of the case, get the lengths of both
// Linked list.
int len1 = getLength(l1);
int len2 = getLength(l2);
Node *lNode = NULL, *sNode = NULL;
Node* temp1 = l1;
Node* temp2 = l2;
// If lengths differ, calculate the smaller Node
// and padd zeros for smaller Node and ensure both
// larger Node and smaller Node has equal length.
if (len1 != len2) {
lNode = len1 > len2 ? l1 : l2;
sNode = len1 > len2 ? l2 : l1;
sNode = paddZeros(sNode, abs(len1 - len2));
}
else {
// If both list lengths are equal, then calculate
// the larger and smaller list. If 5-6-7 & 5-6-8
// are linked list, then walk through linked list
// at last Node as 7 < 8, larger Node is 5-6-8
// and smaller Node is 5-6-7.
while (l1 && l2) {
if (l1->data != l2->data) {
lNode = l1->data > l2->data ? temp1 : temp2;
sNode = l1->data > l2->data ? temp2 : temp1;
break;
}
l1 = l1->next;
l2 = l2->next;
}
}
// If both lNode and sNode still have NULL value,
// then this means that the value of both of the given
// linked lists is the same and hence we can directly
// return a node with value 0.
if (lNode == NULL && sNode == NULL) {
return newNode(0);
}
// After calculating larger and smaller Node, call
// subtractLinkedListHelper which returns the subtracted
// linked list.
borrow = false;
return subtractLinkedListHelper(lNode, sNode);
}
/* A utility function to print linked list */
void printList(struct Node* Node)
{
while (Node != NULL) {
printf("%d ", Node->data);
Node = Node->next;
}
printf("\n");
}
// Driver program to test above functions
int main()
{
Node* head1 = newNode(1);
head1->next = newNode(0);
head1->next->next = newNode(0);
Node* head2 = newNode(1);
Node* result = subtractLinkedList(head1, head2);
printList(result);
return 0;
}
// This code is contributed by Sania Kumari Gupta (kriSania804)
Java
// Java program to subtract smaller valued
// list from larger valued list and return
// result as a list.
import java.util.*;
import java.lang.*;
import java.io.*;
class LinkedList {
static Node head; // head of list
boolean borrow;
/* Node Class */
static class Node {
int data;
Node next;
// Constructor to create a new node
Node(int d)
{
data = d;
next = null;
}
}
/* A utility function to get length of
linked list */
int getLength(Node node)
{
int size = 0;
while (node != null) {
node = node.next;
size++;
}
return size;
}
/* A Utility that padds zeros in front
of the Node, with the given diff */
Node paddZeros(Node sNode, int diff)
{
if (sNode == null)
return null;
Node zHead = new Node(0);
diff--;
Node temp = zHead;
while ((diff--) != 0) {
temp.next = new Node(0);
temp = temp.next;
}
temp.next = sNode;
return zHead;
}
/* Subtract LinkedList Helper is a recursive
function, move till the last Node, and
subtract the digits and create the Node and
return the Node. If d1 < d2, we borrow the
number from previous digit. */
Node subtractLinkedListHelper(Node l1, Node l2)
{
if (l1 == null && l2 == null && borrow == false)
return null;
Node previous
= subtractLinkedListHelper(
(l1 != null) ? l1.next
: null,
(l2 != null) ? l2.next : null);
int d1 = l1.data;
int d2 = l2.data;
int sub = 0;
/* if you have given the value to
next digit then reduce the d1 by 1 */
if (borrow) {
d1--;
borrow = false;
}
/* If d1 < d2, then borrow the number from
previous digit. Add 10 to d1 and set
borrow = true; */
if (d1 < d2) {
borrow = true;
d1 = d1 + 10;
}
/* subtract the digits */
sub = d1 - d2;
/* Create a Node with sub value */
Node current = new Node(sub);
/* Set the Next pointer as Previous */
current.next = previous;
return current;
}
/* This API subtracts two linked lists and
returns the linked list which shall have the
subtracted result. */
Node subtractLinkedList(Node l1, Node l2)
{
// Base Case.
if (l1 == null && l2 == null)
return null;
// In either of the case, get the lengths
// of both Linked list.
int len1 = getLength(l1);
int len2 = getLength(l2);
Node lNode = null, sNode = null;
Node temp1 = l1;
Node temp2 = l2;
// If lengths differ, calculate the smaller
// Node and padd zeros for smaller Node and
// ensure both larger Node and smaller Node
// has equal length.
if (len1 != len2) {
lNode = len1 > len2 ? l1 : l2;
sNode = len1 > len2 ? l2 : l1;
sNode = paddZeros(sNode, Math.abs(len1 - len2));
}
else {
// If both list lengths are equal, then
// calculate the larger and smaller list.
// If 5-6-7 & 5-6-8 are linked list, then
// walk through linked list at last Node
// as 7 < 8, larger Node is 5-6-8 and
// smaller Node is 5-6-7.
while (l1 != null && l2 != null) {
if (l1.data != l2.data) {
lNode = l1.data > l2.data ? temp1 : temp2;
sNode = l1.data > l2.data ? temp2 : temp1;
break;
}
l1 = l1.next;
l2 = l2.next;
}
}
// After calculating larger and smaller Node,
// call subtractLinkedListHelper which returns
// the subtracted linked list.
borrow = false;
return subtractLinkedListHelper(lNode, sNode);
}
// function to display the linked list
static void printList(Node head)
{
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
}
// Driver program to test above
public static void main(String[] args)
{
Node head = new Node(1);
head.next = new Node(0);
head.next.next = new Node(0);
Node head2 = new Node(1);
LinkedList ob = new LinkedList();
Node result = ob.subtractLinkedList(head, head2);
printList(result);
}
}
// This article is contributed by Chhavi
Python
# Python program to subtract smaller valued list from
# larger valued list and return result as a list.
# A linked List Node
class Node:
def __init__(self, new_data):
self.data = new_data
self.next = None
# A utility which creates Node.
def newNode(data):
temp = Node(0)
temp.data = data
temp.next = None
return temp
# A utility function to get length of linked list
def getLength(Node):
size = 0
while (Node != None):
Node = Node.next
size = size + 1
return size
# A Utility that padds zeros in front of the
# Node, with the given diff
def paddZeros( sNode, diff):
if (sNode == None):
return None
zHead = newNode(0)
diff = diff - 1
temp = zHead
while (diff > 0):
diff = diff - 1
temp.next = newNode(0)
temp = temp.next
temp.next = sNode
return zHead
borrow = True
# Subtract LinkedList Helper is a recursive function,
# move till the last Node, and subtract the digits and
# create the Node and return the Node. If d1 < d2, we
# borrow the number from previous digit.
def subtractLinkedListHelper(l1, l2):
global borrow
if (l1 == None and l2 == None and not borrow ):
return None
l3 = None
l4 = None
if(l1 != None):
l3 = l1.next
if(l2 != None):
l4 = l2.next
previous = subtractLinkedListHelper(l3, l4)
d1 = l1.data
d2 = l2.data
sub = 0
# if you have given the value to next digit then
# reduce the d1 by 1
if (borrow):
d1 = d1 - 1
borrow = False
# If d1 < d2, then borrow the number from previous digit.
# Add 10 to d1 and set borrow = True
if (d1 < d2):
borrow = True
d1 = d1 + 10
# subtract the digits
sub = d1 - d2
# Create a Node with sub value
current = newNode(sub)
# Set the Next pointer as Previous
current.next = previous
return current
# This API subtracts two linked lists and returns the
# linked list which shall have the subtracted result.
def subtractLinkedList(l1, l2):
# Base Case.
if (l1 == None and l2 == None):
return None
# In either of the case, get the lengths of both
# Linked list.
len1 = getLength(l1)
len2 = getLength(l2)
lNode = None
sNode = None
temp1 = l1
temp2 = l2
# If lengths differ, calculate the smaller Node
# and padd zeros for smaller Node and ensure both
# larger Node and smaller Node has equal length.
if (len1 != len2):
if(len1 > len2):
lNode = l1
else:
lNode = l2
if(len1 > len2):
sNode = l2
else:
sNode = l1
sNode = paddZeros(sNode, abs(len1 - len2))
else:
# If both list lengths are equal, then calculate
# the larger and smaller list. If 5-6-7 & 5-6-8
# are linked list, then walk through linked list
# at last Node as 7 < 8, larger Node is 5-6-8
# and smaller Node is 5-6-7.
while (l1 != None and l2 != None):
if (l1.data != l2.data):
if(l1.data > l2.data ):
lNode = temp1
else:
lNode = temp2
if(l1.data > l2.data ):
sNode = temp2
else:
sNode = temp1
break
l1 = l1.next
l2 = l2.next
global borrow
# After calculating larger and smaller Node, call
# subtractLinkedListHelper which returns the subtracted
# linked list.
borrow = False
return subtractLinkedListHelper(lNode, sNode)
# A utility function to print linked list
def printList(Node):
while (Node != None):
print (Node.data, end =" ")
Node = Node.next
print(" ")
# Driver program to test above functions
head1 = newNode(1)
head1.next = newNode(0)
head1.next.next = newNode(0)
head2 = newNode(1)
result = subtractLinkedList(head1, head2)
printList(result)
# This code is contributed by Arnab Kundu
C#
// C# program to subtract smaller valued
// list from larger valued list and return
// result as a list.
using System;
public class LinkedList {
static Node head; // head of list
bool borrow;
/* Node Class */
public class Node {
public int data;
public Node next;
// Constructor to create a new node
public Node(int d)
{
data = d;
next = null;
}
}
/* A utility function to get length of
linked list */
int getLength(Node node)
{
int size = 0;
while (node != null) {
node = node.next;
size++;
}
return size;
}
/* A Utility that padds zeros in front
of the Node, with the given diff */
Node paddZeros(Node sNode, int diff)
{
if (sNode == null)
return null;
Node zHead = new Node(0);
diff--;
Node temp = zHead;
while ((diff--) != 0) {
temp.next = new Node(0);
temp = temp.next;
}
temp.next = sNode;
return zHead;
}
/* Subtract LinkedList Helper is a recursive
function, move till the last Node, and
subtract the digits and create the Node and
return the Node. If d1 < d2, we borrow the
number from previous digit. */
Node subtractLinkedListHelper(Node l1, Node l2)
{
if (l1 == null && l2 == null && borrow == false)
return null;
Node previous = subtractLinkedListHelper((l1 != null) ? l1.next : null, (l2 != null) ? l2.next : null);
int d1 = l1.data;
int d2 = l2.data;
int sub = 0;
/* if you have given the value to
next digit then reduce the d1 by 1 */
if (borrow) {
d1--;
borrow = false;
}
/* If d1 < d2, then borrow the number from
previous digit. Add 10 to d1 and set
borrow = true; */
if (d1 < d2) {
borrow = true;
d1 = d1 + 10;
}
/* subtract the digits */
sub = d1 - d2;
/* Create a Node with sub value */
Node current = new Node(sub);
/* Set the Next pointer as Previous */
current.next = previous;
return current;
}
/* This API subtracts two linked lists and
returns the linked list which shall have the
subtracted result. */
Node subtractLinkedList(Node l1, Node l2)
{
// Base Case.
if (l1 == null && l2 == null)
return null;
// In either of the case, get the lengths
// of both Linked list.
int len1 = getLength(l1);
int len2 = getLength(l2);
Node lNode = null, sNode = null;
Node temp1 = l1;
Node temp2 = l2;
// If lengths differ, calculate the smaller
// Node and padd zeros for smaller Node and
// ensure both larger Node and smaller Node
// has equal length.
if (len1 != len2) {
lNode = len1 > len2 ? l1 : l2;
sNode = len1 > len2 ? l2 : l1;
sNode = paddZeros(sNode, Math.Abs(len1 - len2));
}
else {
// If both list lengths are equal, then
// calculate the larger and smaller list.
// If 5-6-7 & 5-6-8 are linked list, then
// walk through linked list at last Node
// as 7 < 8, larger Node is 5-6-8 and
// smaller Node is 5-6-7.
while (l1 != null && l2 != null) {
if (l1.data != l2.data) {
lNode = l1.data > l2.data ? temp1 : temp2;
sNode = l1.data > l2.data ? temp2 : temp1;
break;
}
l1 = l1.next;
l2 = l2.next;
}
}
// After calculating larger and smaller Node,
// call subtractLinkedListHelper which returns
// the subtracted linked list.
borrow = false;
return subtractLinkedListHelper(lNode, sNode);
}
// function to display the linked list
static void printList(Node head)
{
Node temp = head;
while (temp != null) {
Console.Write(temp.data + " ");
temp = temp.next;
}
}
// Driver code
public static void Main(String[] args)
{
Node head = new Node(1);
head.next = new Node(0);
head.next.next = new Node(0);
Node head2 = new Node(1);
LinkedList ob = new LinkedList();
Node result = ob.subtractLinkedList(head, head2);
printList(result);
}
}
// This code has been contributed by 29AjayKumar
JavaScript
<script>
// Javascript program to subtract smaller valued
// list from larger valued list and return
// result as a list.
var head; // head of list
var borrow;
/* Node Class */
class Node {
// Constructor to create a new node
constructor(d) {
this.data = d;
this.next = null;
}
}
/*
A utility function to get length of linked list
*/
function getLength(node) {
var size = 0;
while (node != null) {
node = node.next;
size++;
}
return size;
}
/*
A Utility that padds zeros in
front of the Node, with the given diff
*/
function paddZeros(sNode , diff) {
if (sNode == null)
return null;
var zHead = new Node(0);
diff--;
var temp = zHead;
while ((diff--) != 0) {
temp.next = new Node(0);
temp = temp.next;
}
temp.next = sNode;
return zHead;
}
/*
Subtract LinkedList Helper is a
recursive function, move till the last Node,
and subtract the digits and create the Node
and return the Node. If d1 < d2,
* we borrow the number from previous digit.
*/
function subtractLinkedListHelper(l1, l2) {
if (l1 == null && l2 == null && borrow == false)
return null;
var previous = subtractLinkedListHelper((l1 != null) ?
l1.next : null, (l2 != null) ? l2.next : null);
var d1 = l1.data;
var d2 = l2.data;
var sub = 0;
/*
if you have given the value to next
digit then reduce the d1 by 1
*/
if (borrow) {
d1--;
borrow = false;
}
/*
If d1 < d2, then borrow the number from
previous digit. Add 10 to d1 and set
borrow = true;
*/
if (d1 < d2) {
borrow = true;
d1 = d1 + 10;
}
/* subtract the digits */
sub = d1 - d2;
/* Create a Node with sub value */
var current = new Node(sub);
/* Set the Next pointer as Previous */
current.next = previous;
return current;
}
/*
This API subtracts two linked lists
and returns the linked list which shall
have the subtracted result.
*/
function subtractLinkedList(l1, l2) {
// Base Case.
if (l1 == null && l2 == null)
return null;
// In either of the case, get the lengths
// of both Linked list.
var len1 = getLength(l1);
var len2 = getLength(l2);
var lNode = null, sNode = null;
var temp1 = l1;
var temp2 = l2;
// If lengths differ, calculate the smaller
// Node and padd zeros for smaller Node and
// ensure both larger Node and smaller Node
// has equal length.
if (len1 != len2) {
lNode = len1 > len2 ? l1 : l2;
sNode = len1 > len2 ? l2 : l1;
sNode = paddZeros(sNode, Math.abs(len1 - len2));
}
else {
// If both list lengths are equal, then
// calculate the larger and smaller list.
// If 5-6-7 & 5-6-8 are linked list, then
// walk through linked list at last Node
// as 7 < 8, larger Node is 5-6-8 and
// smaller Node is 5-6-7.
while (l1 != null && l2 != null) {
if (l1.data != l2.data) {
lNode = l1.data > l2.data ? temp1 : temp2;
sNode = l1.data > l2.data ? temp2 : temp1;
break;
}
l1 = l1.next;
l2 = l2.next;
}
}
// After calculating larger and smaller Node,
// call subtractLinkedListHelper which returns
// the subtracted linked list.
borrow = false;
return subtractLinkedListHelper(lNode, sNode);
}
// function to display the linked list
function printList(head) {
var temp = head;
while (temp != null) {
document.write(temp.data + " ");
temp = temp.next;
}
}
// Driver program to test above
var head = new Node(1);
head.next = new Node(0);
head.next.next = new Node(0);
var head2 = new Node(1);
var result = subtractLinkedList(head, head2);
printList(result);
// This code contributed by aashish1995
</script>
Complexity Analysis:
- Time complexity: O(n+m).
As no nested traversal of linked list is needed. - Auxiliary Space: O(n).
If recursive stack space is taken into consideration O(n) space is needed.
Approach 2 (Using 10s complement and linked list addition) :
The approach is similar to this.
The idea is to use 10s complement arithmetic to perform the subtraction.
Number1 - Number2 = Number1 + (- Number2) = Number1 + (10's complement of Number2)
Number1 - Number2 = Number1 + (9's complement of Number2) + 1
The 9's complement can be easily calculated on the go by subtracting each digit from 9. Now, the problem is converted to addition of two numbers represented as linked list.
Follow the steps below to implement the above idea:
- Remove all the initial zeroes from both the linked lists.
- Calculate length of both linked list.
- Determine which number is greater and store it in list 1 (L1) and smaller one in list 2 (L2)
- Now perform addition of linked list while converting L2 to 10's complement
4.1 Initialize carry = 1 because 10's complement = 9's complement + 1
4.2 Reverse both linked list
4.3 For each node, add the value of L1 and 9's complement of value of L2 and carry i.e. sum = (L1 value) + (9 - L2 value) + carry
4.4 Calculate carry = (sum / 10) and sum = (sum % 10) and store sum in a new node - After getting the resulting list, reverse it and remove initial zeroes
- If resulting list becomes empty, add a new node with value 0 (zero), otherwise the remaining list is the answer
Below is the implementation of the above approach:
C++
#include <iostream>
class LinkedList {
private:
struct Node {
int data;
Node* next;
Node(int d) : data(d), next(nullptr) {}
};
Node* head;
// Function to remove leading zeros from the linked list
Node* removeLeadingZeros(Node* head) {
while (head != nullptr && head->data == 0) {
Node* temp = head;
head = head->next;
delete temp;
}
return head;
}
// Function to reverse a linked list
Node* reverse(Node* head) {
Node* prev = nullptr;
Node* current = head;
while (current != nullptr) {
Node* next = current->next;
current->next = prev;
prev = current;
current = next;
}
return prev;
}
// Function to determine which linked list represents the larger number
Node* getLarger(Node* l1, Node* l2) {
while (l1 != nullptr && l2 != nullptr) {
if (l1->data > l2->data) {
return l1;
}
else if (l2->data > l1->data) {
return l2;
}
l1 = l1->next;
l2 = l2->next;
}
// If both numbers are equal, return either linked list
return l1 != nullptr ? l1 : l2;
}
public:
LinkedList() : head(nullptr) {}
// Function to subtract two numbers represented as linked lists
Node* subtract(Node* l1, Node* l2) {
// Remove leading zeros
l1 = removeLeadingZeros(l1);
l2 = removeLeadingZeros(l2);
// Reverse both linked lists
l1 = reverse(l1);
l2 = reverse(l2);
// Determine which linked list represents the larger number
Node* larger = getLarger(l1, l2);
Node* result = nullptr;
Node* prev = nullptr;
int borrow = 0;
// Traverse both linked lists simultaneously and subtract
while (l1 != nullptr || l2 != nullptr) {
int val1 = (l1 != nullptr) ? l1->data : 0;
int val2 = (l2 != nullptr) ? l2->data : 0;
int diff = val1 - val2 - borrow;
if (diff < 0) {
diff += 10;
borrow = 1;
}
else {
borrow = 0;
}
// Create a new node for the result
Node* newNode = new Node(diff);
if (result == nullptr) {
result = newNode;
}
else {
prev->next = newNode;
}
prev = newNode;
// Move to the next nodes
if (l1 != nullptr)
l1 = l1->next;
if (l2 != nullptr)
l2 = l2->next;
}
// Reverse the result linked list
result = reverse(result);
return result;
}
// Function to print the linked list
void printList(Node* head) {
while (head != nullptr) {
std::cout << head->data << " ";
head = head->next;
}
std::cout << std::endl;
}
};
int main() {
LinkedList list;
// Example input
LinkedList::Node* l1 = new LinkedList::Node(1);
l1->next = new LinkedList::Node(0);
l1->next->next = new LinkedList::Node(0);
LinkedList::Node* l2 = new LinkedList::Node(1);
std::cout << "Input Lists:" << std::endl;
list.printList(l1);
list.printList(l2);
LinkedList::Node* result = list.subtract(l1, l2);
std::cout << "Subtraction Result:" << std::endl;
list.printList(result);
// Clean up memory
while (l1 != nullptr) {
LinkedList::Node* temp = l1;
l1 = l1->next;
delete temp;
}
while (l2 != nullptr) {
LinkedList::Node* temp = l2;
l2 = l2->next;
delete temp;
}
while (result != nullptr) {
LinkedList::Node* temp = result;
result = result->next;
delete temp;
}
return 0;
}
Java
class LinkedList {
static class Node {
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
Node head;
// Function to remove leading zeros from the linked list
private Node removeLeadingZeros(Node head)
{
while (head != null && head.data == 0) {
head = head.next;
}
return head;
}
// Function to subtract two numbers represented as
// linked lists
public Node subtract(Node l1, Node l2)
{
// Remove leading zeros
l1 = removeLeadingZeros(l1);
l2 = removeLeadingZeros(l2);
// Reverse both linked lists
l1 = reverse(l1);
l2 = reverse(l2);
// Determine which linked list represents the larger
// number
Node larger = getLarger(l1, l2);
Node result = null;
Node prev = null;
int borrow = 0;
// Traverse both linked lists simultaneously and
// subtract
while (l1 != null || l2 != null) {
int val1 = (l1 != null) ? l1.data : 0;
int val2 = (l2 != null) ? l2.data : 0;
int diff = val1 - val2 - borrow;
if (diff < 0) {
diff += 10;
borrow = 1;
}
else {
borrow = 0;
}
// Create a new node for the result
Node newNode = new Node(diff);
if (result == null) {
result = newNode;
}
else {
prev.next = newNode;
}
prev = newNode;
// Move to the next nodes
if (l1 != null)
l1 = l1.next;
if (l2 != null)
l2 = l2.next;
}
// Reverse the result linked list
result = reverse(result);
return result;
}
// Function to reverse a linked list
private Node reverse(Node head)
{
Node prev = null;
Node current = head;
Node next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
return prev;
}
// Function to determine which linked list represents
// the larger number
private Node getLarger(Node l1, Node l2)
{
while (l1 != null && l2 != null) {
if (l1.data > l2.data) {
return l1;
}
else if (l2.data > l1.data) {
return l2;
}
l1 = l1.next;
l2 = l2.next;
}
// If both numbers are equal, return either linked
// list
return l1 != null ? l1 : l2;
}
// Function to print the linked list
public void printList(Node head)
{
while (head != null) {
System.out.print(head.data + " ");
head = head.next;
}
System.out.println();
}
public static void main(String[] args)
{
LinkedList list = new LinkedList();
// Example input
Node l1 = new Node(1);
l1.next = new Node(0);
l1.next.next = new Node(0);
Node l2 = new Node(1);
System.out.println("Input Lists:");
list.printList(l1);
list.printList(l2);
Node result = list.subtract(l1, l2);
System.out.println("Subtraction Result:");
list.printList(result);
}
}
Python
class LinkedList:
class Node:
def __init__(self, d):
self.data = d
self.next = None
def __init__(self):
self.head = None
# Function to remove leading zeros from the linked list
def removeLeadingZeros(self, head):
while head and head.data == 0:
head = head.next
return head
# Function to subtract two numbers represented as linked lists
def subtract(self, l1, l2):
# Remove leading zeros
l1 = self.removeLeadingZeros(l1)
l2 = self.removeLeadingZeros(l2)
# Reverse both linked lists
l1 = self.reverse(l1)
l2 = self.reverse(l2)
# Determine which linked list represents the larger number
larger = self.getLarger(l1, l2)
result = None
prev = None
borrow = 0
# Traverse both linked lists simultaneously and subtract
while l1 or l2:
val1 = l1.data if l1 else 0
val2 = l2.data if l2 else 0
diff = val1 - val2 - borrow
if diff < 0:
diff += 10
borrow = 1
else:
borrow = 0
# Create a new node for the result
new_node = self.Node(diff)
if not result:
result = new_node
else:
prev.next = new_node
prev = new_node
# Move to the next nodes
if l1:
l1 = l1.next
if l2:
l2 = l2.next
# Reverse the result linked list
result = self.reverse(result)
return result
# Function to reverse a linked list
def reverse(self, head):
prev = None
current = head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
return prev
# Function to determine which linked list represents the larger number
def getLarger(self, l1, l2):
while l1 and l2:
if l1.data > l2.data:
return l1
elif l2.data > l1.data:
return l2
l1 = l1.next
l2 = l2.next
# If both numbers are equal, return either linked list
return l1 if l1 else l2
# Function to print the linked list
def printList(self, head):
while head:
print(head.data, end=" ")
head = head.next
print()
if __name__ == "__main__":
# Example input
list_obj = LinkedList()
l1 = list_obj.Node(1)
l1.next = list_obj.Node(0)
l1.next.next = list_obj.Node(0)
l2 = list_obj.Node(1)
print("Input Lists:")
list_obj.printList(l1)
list_obj.printList(l2)
result = list_obj.subtract(l1, l2)
print("Subtraction Result:")
list_obj.printList(result)
JavaScript
class LinkedList {
constructor() {
this.head = null;
}
static Node = class {
constructor(d) {
this.data = d;
this.next = null;
}
};
// Function to remove leading zeros from the linked list
removeLeadingZeros(head) {
while (head !== null && head.data === 0) {
head = head.next;
}
return head;
}
// Function to reverse a linked list
reverse(head) {
let prev = null;
let current = head;
let next = null;
while (current !== null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
return prev;
}
// Function to determine which linked list represents
// the larger number
getLarger(l1, l2) {
while (l1 !== null && l2 !== null) {
if (l1.data > l2.data) {
return l1;
} else if (l2.data > l1.data) {
return l2;
}
l1 = l1.next;
l2 = l2.next;
}
// If both numbers are equal, return either linked
// list
return l1 !== null ? l1 : l2;
}
// Function to print the linked list
printList(head) {
let result = "";
while (head !== null) {
result += head.data + " ";
head = head.next;
}
console.log(result);
}
// Function to subtract two numbers represented as
// linked lists
subtract(l1, l2) {
// Remove leading zeros
l1 = this.removeLeadingZeros(l1);
l2 = this.removeLeadingZeros(l2);
// Reverse both linked lists
l1 = this.reverse(l1);
l2 = this.reverse(l2);
// Determine which linked list represents the larger
// number
let larger = this.getLarger(l1, l2);
let result = null;
let prev = null;
let borrow = 0;
// Traverse both linked lists simultaneously and
// subtract
while (l1 !== null || l2 !== null) {
let val1 = l1 !== null ? l1.data : 0;
let val2 = l2 !== null ? l2.data : 0;
let diff = val1 - val2 - borrow;
if (diff < 0) {
diff += 10;
borrow = 1;
} else {
borrow = 0;
}
// Create a new node for the result
let newNode = new LinkedList.Node(diff);
if (result === null) {
result = newNode;
} else {
prev.next = newNode;
}
prev = newNode;
// Move to the next nodes
if (l1 !== null) l1 = l1.next;
if (l2 !== null) l2 = l2.next;
}
// Reverse the result linked list
result = this.reverse(result);
return result;
}
static main() {
let list = new LinkedList();
// Example input
let l1 = new LinkedList.Node(1);
l1.next = new LinkedList.Node(0);
l1.next.next = new LinkedList.Node(0);
let l2 = new LinkedList.Node(1);
console.log("Input Lists:");
list.printList(l1);
list.printList(l2);
let result = list.subtract(l1, l2);
console.log("Subtraction Result:");
list.printList(result);
}
}
LinkedList.main();
Time complexity: O(n), As no nested traversal of linked list is needed.
Auxiliary Space: O(n), O(n) space is needed to store the resultant list, but it can be made to O(1) space by storing the result in original linked list.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem