Given two linked lists that represent two large positive numbers. Subtract the smaller number from 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 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 Input : l1 = 1 -> 0 -> 0 -> NULL, l2 = 1 -> NULL Output : 0->9->9->NULL Input : l1 = 7-> 8 -> 6 -> NULL, l2 = 7 -> 8 -> 9 NULL Output : 3->NULL
Following are the steps.
1) Calculate sizes of given two linked lists.
2) If sizes not are same, then append zeros in smaller linked list.
3) If size are same, then follow below steps:
….a) Find the smaller valued linked list.
….b) One by one subtract nodes of smaller sized linked list from larger size. Keep track of borrow while subtracting.
Following is the implementation of the above approach.
0 9 9
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
- Add Two Numbers Represented by Linked Lists | Set 3
- Add two numbers represented by linked lists | Set 2
- Add two numbers represented by linked lists | Set 1
- 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