/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
var list = new List<ListNode>();
var temp1 = l1;
var temp2 = l2;
var step = ;
while (l1 != null || l2 != null)
{
var v1 = ;
var v2 = ;
if (l1 == null)
{
l1 = new ListNode();
}
v1 = l1.val;
l1 = l1.next; if (l2 == null)
{
l2 = new ListNode();
}
v2 = l2.val;
l2 = l2.next; var cur = v1 + v2 + step;
var result = ;
if (cur >= )
{
step = ;
result = cur % ;
}
else
{
step = ;
result = cur;
}
list.Add(new ListNode(result));
}
if (step == )
{
list.Add(new ListNode());
} for (int i = ; i < list.Count - ; i++)
{
list[i].next = list[i + ];
}
var head = list[];
return head;
}
}
https://leetcode.com/problems/add-two-numbers/#/description
补充python实现:
class Solution:
def addTwoNumbers(self, l1: 'ListNode', l2: 'ListNode') -> 'ListNode':
headnode = ListNode(0)
temp = headnode
carry = 0
while l1!=None or l2!=None:
if l1==None:
l1 = ListNode(0)
if l2==None:
l2 = ListNode(0)
cur = l1.val + l2.val + carry
if cur // 10 > 0:
carry = 1
else:
carry = 0
cur = cur % 10
temp.next = ListNode(cur)
temp = temp.next
l1 = l1.next
l2 = l2.next
if carry > 0:
temp.next = ListNode(carry)
return headnode.next