leetcode -- Algorithms -- 2_ Add two numbers
Solution
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): dummy = cur = ListNode(0) carry = 0 while l1 or l2 or carry: if l1: carry += l1.val l1 = l1.next if l2: carry += l2.val l2 = l2.next cur.next = ListNode(carry%10) cur = cur.next carry //= 10 return dummy.next
oder mit recursive :
public: ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { if(l1 == NULL) return l2; if(l2 == NULL) return l1; if(l1->val < l2->val) { l1->next = mergeTwoLists(l1->next, l2); return l1; } else { l2->next = mergeTwoLists(l2->next, l1); return l2; } } };
而返回一个新的链表,只需要给指向第一个数据的指针地址就可以。
Die analysis ist sehr gut. Finden Sie die Details mit den Link.
https://leetcode.com/articles/add-two-numbers/