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 one.
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 smaller linked list.
- If size are same, then follow 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 contribute.geeksforgeeks.org or mail your article to email@example.com. 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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Add two numbers represented by linked lists | Set 2
- Add two numbers represented by linked lists | Set 1
- Add Two Numbers Represented by Linked Lists | Set 3
- Compare numbers represented by Linked Lists
- Multiply two numbers represented by Linked Lists
- Multiply two numbers represented as linked lists into a third list
- Compare two strings represented as linked lists
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
- Create a linked list from two linked lists by choosing max element at each position
- Add one to a number represented as linked list | Set 2
- Add 1 to a number represented as linked list
- Reverse all the word in a String represented as a Linked List
- Add two numbers represented by two arrays
- Multiply Large Numbers represented as Strings
- Modulo power for large numbers represented as strings
- Identical Linked Lists
- Check if two Linked Lists are permutations of each other
- Union and Intersection of two Linked Lists
- First common element in two linked lists
- Merge K sorted linked lists | Set 1