Given the head pointers of two linked lists, add them and return the new linked list. Each linked list represents an integer number (each node is a digit).
Question
Given the head pointers of two linked lists, add them and return the new linked list.
Each linked list represents an integer number (each node is a digit).
Solution
Here is a Python solution for the problem:
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
def addTwoLists(first, second):
prev = temp = None
carry = 0
while(first is not None or second is not None):
fdata = 0 if first is None else first.data
sdata = 0 if second is None else second.data
Sum = carry + fdata + sdata
carry = 1 if Sum >= 10 else 0
Sum = Sum if Sum < 10 else Sum % 10
temp = Node(Sum)
if head is None:
head = temp
else :
prev.next = temp
prev = temp
if first is not None:
first = first.next
if second is not None:
second = second.next
if carry > 0:
temp.next = Node(carry)
return head
This Python function addTwoLists
takes two linked lists first
and second
as input. It creates a new linked list where each node is the sum of the corresponding nodes in the input lists. If the sum is greater than 10, it carries the value to the next node.
The Node
class is a simple linked list node class with a data
field for storing the node's value and a next
field for pointing to the next node in the list.
The addTwoLists
function iterates over the two input lists simultaneously. For each pair of nodes, it adds their values together (along with any carry value from the previous node), then creates a new node with the sum. If the sum is 10 or more, it sets the carry value to 1 and reduces the sum by 10. The new node is then added to the output list.
If there is a carry value left over after all nodes have been processed, a final node is added to the output list with this carry value.
Finally, the function returns the head of the new linked list.
Similar Questions
A linked list whose last node points back to both the head node and the previous node instead of containing the null pointer ____________
In a doubly linked list, the number of pointers affected for an insertion operation will be
n a doubly linked list, how many pointers does each node have?a.Oneb.Fourc.Threed.Two
In a doubly linked list, how many pointers need to be updated to insert a new node at the end? Group of answer choices3421
Insertion of an element at the middle of a linked list requires the modification of how many pointers?a.4b.3c.2d.1
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.