![]() |
VOOZH | about |
You are given two linked lists representing two large positive numbers. The linked lists represent these two numbers, subtract the smaller number from the larger one and return the head of the linked list representing the result.
The linked list does not contain leading zeros, except for the number zero itself.
Examples:
Input: l1 = 1 -> 0 -> 0 -> NULL, l2 = 1 -> NULL
Output: 9->9->NULL
Explanation: Number represented as lists are 100 and 1, so 100 - 1 is 99Input: 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.
Table of Content
We subtract two numbers represented as linked lists where digits are stored in forward order. Since subtraction naturally happens from the rightmost digit, we use recursion to reach the end of the lists and perform subtraction while backtracking. Before that, we equalize their sizes by padding zeros. During subtraction, we handle borrow just like in manual subtraction and finally remove leading zeros.
9 9
In this approach, we reverse both linked lists so that subtraction can be done from the least significant digit (just like normal subtraction). Then we traverse both lists together, subtract digits while handling borrow, and build the result list. Finally, we reverse the result back and remove any leading zeros.
Below is the implementation of the above approach:
9 9