[leetcode题解]2.Add Two Numbers

leetcode,2,Add Two Numbers,给定两个单链表,将两个单链表从左到右进行相加,题目中已知不会出现前导0。本题可以直接对两单链表同时进行遍历相加即可,保留一个进位,检测最后是否要进行正确进位,python和c++两种语言写,代码如下:

python代码

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        :author: 凌风技术站-iaccepted
        """
        a, b, c = 0, 0, 0
        pre = ListNode(-1)
        tail = pre
        
        while l1 is not None or l2 is not None:
            a = 0
            if l1 is not None:
                a = l1.val
                l1 = l1.next
            
            b = 0
            if l2 is not None:
                b = l2.val
                l2 = l2.next
            c += (a + b)
            node = ListNode(c % 10)
            c //= 10
            tail.next = node
            tail = tail.next
        if c != 0:
            node = ListNode(c)
            tail.next = node
            tail = tail.next
        tail.next = None
        return pre.next

        
c++代码

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) 
    {
        ListNode *pre = new ListNode(-1);
        ListNode *tail = pre;
        
        int c = 0, sum = 0;
        while(l1 != NULL && l2 != NULL)
        {
            sum = l1->val + l2->val + c;
            
            c = sum / 10;
            sum %= 10;
            ListNode *node = new ListNode(sum);
            tail->next = node;
            tail = node;
            
            l1 = l1->next;
            l2 = l2->next;
        }
        
        ListNode *l = l1;
        if (l1 == NULL)l = l2;
        
        while(l != NULL)
        {
            sum = l->val + c;
            c = sum / 10;
            sum %= 10;
            ListNode *node = new ListNode(sum);
            tail->next = node;
            tail = node;
            
            l = l->next;
        }
        
        if (c != 0)
        {
            ListNode *node = new ListNode(c);
            tail->next = node;
        }
        
        return pre->next;
    }
};

本文遵从CC3.0协议转载请注明:转自凌风技术站

本文标题:[leetcode题解]2.Add Two Numbers

本文链接地址:http://www.iaccepted.net/algorithm/leetcode/109.html

相关文章



发表评论

电子邮件地址不会被公开。 必填项已用*标注