leetcode算法题库-两数相加

两数相加

给出两个非空的链表用来表示两个非负的整数。其中,它们各自的位数是按照逆序 的方式存储的,并且它们的每个节点只能存储 一位数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
实例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

C语言

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
    struct ListNode* p1 = l1;
    struct ListNode* p2 = l2;
    //申请一个新的空链表
    struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode));
    head->next = NULL;
    //申请一个尾指针,后面采用的是尾插法增加新节点
    struct ListNode* tail = head;
    struct ListNode* p3;
    int carry = 0;
    int temp = 0;
    while(p1 && p2) //两个链表的节点还是一一对应的时候,走该分支
    {
        //申请新的节点
        p3 = (struct ListNode*)malloc(sizeof(struct ListNode));
        temp = p1->val + p2->val + carry;
        if(temp > 9)
        {
            carry = 1;
            p3->val = temp % 10;
        }
        else
        {
            carry = 0;
            p3->val = temp;
        }
        tail->next = p3;//尾指针指向刚才生成的新节点
        tail = p3;//让新的节点变成尾指针

        p1 = p1->next;
        p2 = p2->next;

    }
    while(p2){
        p3 = (struct ListNode*)malloc(sizeof(struct ListNode));
        temp = p2->val + carry;
        if(temp>9){
            carry = 1;
            p3->val = temp%10;
        }
        else{
            carry = 0;
            p3->val = temp;
        }
        tail->next = p3;
        tail = p3;
        p2 = p2->next;
    }
    while(p1){
        p3 = (struct ListNode*)malloc(sizeof(struct ListNode));
        temp = p1->val + carry;
        if(temp>9){
            carry = 1;
            p3->val = temp%10;
        }
        else{
            carry = 0;
            p3->val = temp;
        }
        tail->next = p3;
        tail = p3;
        p1 = p1->next;
    }
    if(carry==1){
        p3 = (struct ListNode*)malloc(sizeof(struct ListNode));
        p3->val = 1;
        tail->next = p3;
        tail = p3;
    }
    tail->next = NULL;
    return head->next;
}

python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        re = ListNode(0)
        r = re
        carry = 0
        while(l1 or l2):
            x = l1.val if l1 else 0
            y = l2.val if l2 else 0
            s = carry + x + y
            carry = s//10
            r.next = ListNode(s%10)
            r = r.next
            if(l1!=None):
                l1 = l1.next
            if(l2!=None):
                l2 = l2.next
        if(carry>0):
            r.next = ListNode(1)
        return re.next

本篇文档完成于2020/5/2。

猜你喜欢

转载自blog.csdn.net/qq_36662353/article/details/105893468
今日推荐