leetcode 2. Add Two Numbers python实现的理解,结点,单链表的应用,大数,进位的问题

来源:互联网 发布:人工智能需要哪些技术 编辑:程序博客网 时间:2024/06/06 00:02

题目:

You are given two linked lists representing two non-negative numbers. 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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8


题意:

给定两个单链表,每个单链表的每个节点存储一个非负整数。两个单链表数据相加,但是每个节点只能存储一个数字(即遇到10要进位),返回相加后的单链表。


代码:

class Solution:
    def addTwoNumbers(self, l1, l2):
        if l1 is None:
            return l2
        elif l2 is None:
            return l1
        else:          
            carry = 0
            ret =ListNode(0)
            ret_Last = ret
            
            while(l1 or l2):
                sum = 0
                if(l1):
                    sum = l1.val
                    l1 = l1.next
                if(l2):
                    sum += l2.val
                    l2 = l2.next
                sum += carry
                ret_Last.next = ListNode(sum%10)
                ret_Last = ret_Last.next
                carry = (sum >= 10)
            if(carry):
                ret_Last.next =ListNode(1)
            ret_Last = ret.next
            del ret
            return ret_Last 



0 0
原创粉丝点击