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 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
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Add two numbers represented by linked lists | Set 1
- Add two numbers represented by linked lists | Set 2
- 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 1 to a number represented as linked list
- Add one to a number represented as linked list | Set 2
- 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
- First common element in two linked lists
- Merge Sort for Linked Lists
- Intersection of two Sorted Linked Lists
- Merge two sorted linked lists