LeetCode 2. 两数相加 (大数相加 + 链表)

两数相加
注意点:在链表没有遍历完或者还有余数没有加上的时候,都要继续进行。

/**
 * 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* pre = new ListNode,*cur = pre; // pre 是哨兵
        int t = 0;
        while(l1 && l2){
    
    
            t += l1->val + l2->val;
            l1 = l1->next;
            l2 = l2->next;
            ListNode* node = new ListNode(t%10);
            cur->next = node;
            cur = node;
            t /= 10;
        }
        ListNode* l = l1?l1:l2;
        while(l){
    
    
            t += l->val;
            l = l->next;
            ListNode* node = new ListNode(t%10);
            cur->next = node;
            cur = node;
            t/= 10;
        }
        while(t){
    
    
            ListNode* node = new ListNode(t%10);
            cur->next = node;
            cur = node;
            t/= 10;                        
        }
        return pre->next;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_44846324/article/details/108923058