You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
Example:
Input: (7 -> 1 -> 6) + (5 -> 9 -> 2). That is, 617 + 295.
Output: 2 -> 1 -> 9. That is, 912.
Follow Up: Suppose the digits are stored in forward order. Repeat the above problem.
Example:
Input: (6 -> 1 -> 7) + (2 -> 9 -> 5). That is, 617 + 295.
Output: 9 -> 1 -> 2. That is, 912.
Solutions
Solution 1: Simulation
We traverse two linked lists \(l_1\) and \(l_2\) simultaneously, and use a variable \(carry\) to indicate whether there is a carry-over currently.
During each traversal, we take out the current digit of the corresponding linked list, calculate the sum of them and the carry-over \(carry\), then update the value of the carry-over, and finally add the value of the current digit to the answer linked list. The traversal ends when both linked lists have been traversed and the carry-over is \(0\).
Finally, we return the head node of the answer linked list.
The time complexity is \(O(\max(m, n))\), where \(m\) and \(n\) are the lengths of the two linked lists respectively. We need to traverse all positions of the two linked lists, and it only takes \(O(1)\) time to process each position. Ignoring the space consumption of the answer, the space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 910111213141516171819
# Definition for singly-linked list.# class ListNode:# def __init__(self, x):# self.val = x# self.next = NoneclassSolution:defaddTwoNumbers(self,l1:ListNode,l2:ListNode)->ListNode:dummy=ListNode()carry,curr=0,dummywhilel1orl2orcarry:s=(l1.valifl1else0)+(l2.valifl2else0)+carrycarry,val=divmod(s,10)curr.next=ListNode(val)curr=curr.nextl1=l1.nextifl1elseNonel2=l2.nextifl2elseNonereturndummy.next
1 2 3 4 5 6 7 8 9101112131415161718192021222324
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */classSolution{publicListNodeaddTwoNumbers(ListNodel1,ListNodel2){ListNodedummy=newListNode(0);intcarry=0;ListNodecur=dummy;while(l1!=null||l2!=null||carry!=0){ints=(l1==null?0:l1.val)+(l2==null?0:l2.val)+carry;carry=s/10;cur.next=newListNode(s%10);cur=cur.next;l1=l1==null?null:l1.next;l2=l2==null?null:l2.next;}returndummy.next;}}
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */funcaddTwoNumbers(l1*ListNode,l2*ListNode)*ListNode{dummy:=&ListNode{}cur:=dummycarry:=0forl1!=nil||l2!=nil||carry>0{ifl1!=nil{carry+=l1.Vall1=l1.Next}ifl2!=nil{carry+=l2.Vall2=l2.Next}cur.Next=&ListNode{Val:carry%10}cur=cur.Nextcarry/=10}returndummy.Next}