美文网首页
leetcode 2. 两数相加

leetcode 2. 两数相加

作者: Source_Chang | 来源:发表于2020-10-19 14:57 被阅读0次

    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;
        }
    };
    

    相关文章

      网友评论

          本文标题:leetcode 2. 两数相加

          本文链接:https://www.haomeiwen.com/subject/yyrwpktx.html