兩數相加

31 阅读1分钟

題目

leetcode.cn/problems/ad…

題解

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode dummy;
        ListNode *current=&dummy;
        int carry=0;
        while(l1||l2||carry){
            int sum=carry;
            if(l1){
                sum+=l1->val;
                l1=l1->next;
            }
            if(l2){
                sum+=l2->val;
                l2=l2->next;
            }
            carry=sum/10;
            current->next=new ListNode(sum%10);
            current=current->next;
        }
        return dummy.next;
    }
};
  • 从最低位开始相加(链表头部)

  • 处理每一位的 进位

  • 若有剩余进位,要在最后加一个节点

l1.vall2.valcarrysum新节点值下一位carry
250770
4601001
341880