Add two numbers represented by linked listsLinked listIn Computer Science, linked list is a data structure where data is stored in a linear fashion but not stored in the contiguous memory location. There is a series of nodes connected where each node contains the data value and address of the next value. Problem statement: Here, we are given two linked lists, and we have to add these two linked lists considering them as two numbers, and return the sum in the form of linked lists. For example: We have two linked lists like: In the above example, list1 represents the number 2342, and list2 represents the number 95607. If we sum up these two numbers, we will get the result as 97949, and we will return this number as a linked list. The most significant digit of any number will be the head of the linked list, and the least significant digit of the number will be the last node of the linked list. Method 1The most straightforward approach to solve the problem is that we will convert both lists into equivalent integer values, and we will store the sum of these two numbers into an integer value. Now we will convert this integer into a linked list. Java Code: Output: Explanation
Method 2We will traverse both lists and add the values during traversal. In this approach, we will reverse both lists and start adding elements. We will maintain a carry variable which will be propagated in the next iteration again and again. If carry remains 1 in the end, we will create the extra node of that carry. Else, we will not since the resultant linked list will be in the reverse order, so we will reverse it again to get the actual order. Java code: Time complexity: O(N) Space complexity: O(N) |