Leetcode2 两数相加C++ / Python

题目描述

英文:

You are given two non-empty linked lists representing two non-negative integers.
The digits are stored in reverse order and each of their nodes contain a single digit.
Add the two numbers and return it as a linked list.

Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
2 -> 4 -> 3 + 5 -> 6 -> 4
7 -> 0 -> 8

中文:

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

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

解题思路:


C++:
在这里可以设置一个进位为int carry = 0来记录进位,注意这里用三个指针p q curr 分别记录了 l1 l2, result 的
头部。然后用p q遍历 l1 与 l2,条件为两个指针至少一个不为空,若其中一个的指针为空时 将其的 val 设置为0,最后将相加得到的结果放入curr中,然后程序最后return result->next。如果最终得到的carry = 1时将其添加到curr->next

Python:
在Python中同样设置进位 val = 0 同样当l1,l2不为空时返回其val 为空时返回0。利用divmod函数来计算其中的
进位 与 相加的和,并将和存入lastnode中最后返回。同样以一个prenode来事先记录住lastnode的头部,最后
返回一个prenode.next

C++代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 * 
 * 2 -> 4 -> 3      +     5 -> 6 -> 4
 * 
 * 7 -> 0 -> 8
 */
#include<iostream>
using namespace std;

class ListNode
{
public:
    ListNode()
    {
        next = 0;
    }
    ListNode(int el,ListNode* next = 0)
    {
        this->val = el;
        this->next = next;
    }
    int val;
    ListNode* next;
};


class Solution                    //核心代码
{
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
    {
        ListNode* result = new ListNode(0);
        ListNode* p = l1;
        ListNode* q = l2;
        ListNode* curr = result;         //注意一定要用一个指针记录result的头部,不然最后return时无法返回链表的头
        int carry = 0;                   //进位
        while(p != 0 || q != 0 )
        {
            int x = (p != 0)? p->val:0;    //若p不为空时取p里面的val,否则为0
            int y = (q != 0)? q->val:0;    //若q不为空时取q里面的val,否则为0
            int sum = x + y + carry;
            carry = sum/10;
            curr->next = new ListNode(sum%10);
            curr = curr->next;
            if(p!=0)
            {
                p = p->next;
            }
            if(q!=0)
            {
                q = q->next;
            }
        }
        if(carry!=0)
        {
            curr->next = new ListNode(carry);         //若最后carry为一时则进一位
        }
        return result->next;
    }
};


int main()
{
    ListNode* l1 = new ListNode(2);
    l1->next = new ListNode(4);
    l1->next->next = new ListNode(3);
    ListNode* l2 = new ListNode(5);
    l2->next = new ListNode(6);
    l2->next->next = new ListNode(4);
    Solution s;
    ListNode* temp = s.addTwoNumbers(l1,l2);
    while (temp!=0)
    {
        cout<<temp->val<<" ";
        temp = temp->next;
    }
    system("pause");
    return 0;
}

Python代码:

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:                           #核心函数
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:   		#->函数返回链表
        prenode = ListNode(0)
        lastnode = prenode
        val = 0        				#记录进位
        while val or l1 or l2:
            val, cur = divmod(val + (l1.val if l1 else 0) + (l2.val if l2 else 0), 10)
            				# divmod 后面的返回一个参数商和参数取模的元组
            				#即 tuple(a//b , a%b)
            lastnode.next = ListNode(cur)
            lastnode = lastnode.next
            l1 = l1.next if l1 else None
            l2 = l2.next if l2 else None
        return prenode.next


def generateList(l: list) -> ListNode:
    prenode = ListNode(0)
    lastnode = prenode
    for val in l:
        lastnode.next = ListNode(val)
        lastnode = lastnode.next
    return prenode.next

def printList(l: ListNode):
    while l:
        print("%d, " %(l.val), end = '')
        l = l.next
    print('')

if __name__ == "__main__":
    l1 = generateList([243])
    l2 = generateList([5,6,4])
    printList(l1)
    printList(l2)
    s = Solution()
    sum = s.addTwoNumbers(l1, l2)
    printList(sum)

总结:

两数链表相加,即先分别用两个指针的来遍历链表,然后设置一个进位,最后将得到的结果放在声明的指针的
副本中,最后返回声明指针的next即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值