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 extra leading zeros in input lists.
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.
Approach: Following are the steps.
- 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.
0 9 9
- Time complexity: O(n).
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.
This article is contributed by Mu Ven. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above