Be the first user to complete this post
|
Add to List |
34. Add two numbers represented by a linked list, Numbers are Stored in REVERSE order
Objective: Two numbers represented by a linked list where each node contains single digit. The digits are stored in REVERSE order, means head is pointing to the first digit of the number.
Input: Two numbers represented by Linked Lists
Output: Addition of two numbers represented by a Linked List.
Example:
First Number in REVERSE order: 5957 Second Number in REVERSE order : 59 Addition in REVERSE order : 0967 Actual Result in FORWARD ORDER : 9670
Approach:
- Initialize carry =0 and newHead for Result linked list
- Iterate both the linked lists at the same time.
- Get the sum S = node value from both the lists + carry (if any of the list is over, take 0 as node value from that list)
- Reset carry=0
- If S > 10, then do S = S-10, carry=1.
- Create a new node with value S and add it to the newHead.
- Repeat the above step until both the lists are over.
- At the end, check if carry =1, create a node with value 1 and add to result list.
- Return result list.
- Look at the display functions below for printing linked lists in forward and reverse order.
Example:
First Number: 179 Second Number: 86
First Number in REVERSE order: 5957 Second Number in REVERSE order : 59 Addition in REVERSE order : 0967 Actual Result in FORWARD ORDER : 9670
Also Read - Adding Two Numbers with Linked Lists