2、Add Two Numbers(两个数的求和)

这道题的题目意思很简单,就是求两个非负整数的和,只不过每一个数都是由链表表示,并且链表的数据元素的顺序,和整数的每一位数字的顺序是相反的,比如342,链表表示为2->4->3。因此,计算出的结果的链表存放元素的顺序也是反的。这里,我们只要同时遍历两个链表,然后将每一个元素相加,对每一位上的和进行取余,然后保留进位符,在下一个位置上进行相加。遍历两个链表后,最后还要判断一次进位符,如果不为0,则开辟节点保留。

C语言:

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode *head,*rear = NULL,*p;
    int value = 0;
    while(l1 || l2)
    {
        if(l1)
        {
            value += l1->val;
            l1 = l1->next;
        }
        if(l2)
        {
            value += l2->val;
            l2 = l2->next;
        }
        p = (struct ListNode *)malloc(sizeof(struct ListNode));
        p->val = value%10;
        value = value / 10;
        p->next = NULL;
        if(rear == NULL)
        {
            rear = p;
            head = rear;
        }
        else
        {
            rear->next = p;
            rear = p;
        }
    }
    if(value)
    {
        p = (struct ListNode *)malloc(sizeof(struct ListNode));
        p->val = value;
        p->next = NULL;
        rear->next = p;
    }
    return head;
}

python:

def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        head = None
        rear = None
        value = 0
        while ( l1) or ( l2):
            if  l1:
                value += l1.val
                l1 = l1.next
                
            if  l2:
                value += l2.val
                l2 = l2.next
                
            temp = ListNode(value%10)
            value = value/10
            if rear == None:
                rear = temp
                head = rear
            else:
                rear.next = temp
                rear = temp
                
        if value:
            temp = ListNode(value)
            rear.next = temp
            
        return head

Python版本的结果令我激动了三秒钟......

然后,我又继续学习了

你可能感兴趣的:(leetcode刷题记录)