leetcode 2. 两数相加

2020-10-19  本文已影响0人  Source_Chang

leetcode

链表结构:
C++:

struct ListNode {
public:
    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) {}
};

C++:

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        
        ListNode *head = NULL;
        ListNode *node = NULL;
        int offset = 0;
        while ( l1 || l2 ) {
            
            int left = 0;
            if ( l1 ) {
                
                left = l1 -> val;
                l1 = l1 -> next;
            }
            
            int right = 0;
            if ( l2 ) {
                
                right = l2 -> val;
                l2 = l2 -> next;
            }
            
            int sum = left + right + offset;
            offset = sum / 10;
            int rest = sum % 10;
            
            if ( node ) {
                
                if ( node -> next ) {
                    
                    node -> next -> val = rest;
                    
                } else {
                    
                    node -> next = new ListNode(rest);
                }
                
                node = node -> next;
                
            } else {
                
                node = new ListNode(rest);
            }
            
            if ( !head ) {
                
                head = node;
            }
        }
        if ( offset != 0 ) {
            
            if ( node ) {
                
                if ( node -> next ) {
                    
                    node -> next -> val = offset;
                    
                } else {
                    
                    node -> next = new ListNode(offset);
                }
                
                node = node -> next;
            }
        }
        if ( node ) {
            
            node -> next = NULL;
        }
        
        return head;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读