Add two numbers represented by linked lists.
Example 1:
Input:
List1: 5->6->3 // represents number 563
List2: 8->4->2 // represents number 842
Output:
Resultant list: 1->4->0->5 // represents number 1405
Explanation: 563 + 842 = 1405
Example 2:
Input:
List1: 7->5->9->4->6 // represents number 75946
List2: 8->4 // represents number 84
Output:
Resultant list: 7->6->0->3->0// represents number 76030
Explanation: 75946+84=76030
1. Node Class:-
A Node class is defined to represent the nodes of a singly linked list. Each node has an integer data and a
pointer next to the next node.
2. newNode Function:-
This function creates and returns a new node with the given data value.
3. push Function:-
The push function inserts a new node with the provided data at the beginning of a linked list. It updates
the head_ref pointer to point to the new node.
4. addTwoLists Function:-
This function takes two linked lists, first and second, representing the numbers to be added.
It iterates through both lists while adding corresponding elements and maintaining a carry value.
It calculates the sum, updates the carry, and creates a new node with the sum as the data value.
The resulting nodes are linked to create the sum list.
If there is a carry at the end of the addition, it is added as a new node.
5. reverse Function:-
This function reverses a given linked list using a recursive approach.
It reverses the order of nodes in the linked list.
6. printList Function:-
This utility function is used to print the elements of a linked list.
7. Main Function:-
In the main function, two linked lists, first and second, are created to represent two numbers. These lists
are initialized in reverse order because the addTwoLists function expects them in reverse order.
The addTwoLists function is called to add the two numbers represented by the linked lists.
After adding the numbers, the result is reversed again to get the correct order.
The resulting linked list representing the sum is printed.