Leetcode题解(Python): 2.Add Two Numbers

来源:互联网 发布:微信三级分销拼团源码 编辑:程序博客网 时间:2024/06/01 10:39

【题目】
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

Subscribe to see which companies asked this question

【题解】

# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def addTwoNumbers(self, l1, l2):        """        :type l1: ListNode        :type l2: ListNode        :rtype: ListNode        """        carry = 0;//用于记录加法进位        tmp1 = l1;//保存起始指针        pre = None;//记录遍历时的前一个节点        //1、计算链表12一一对应的节点的值        while (l1 != None) and (l2 != None):            sum = l1.val + l2.val + carry;            if sum >= 10:                l1.val = sum - 10;                carry = 1;            else:                l1.val = sum;                carry = 0;            pre = l1;//记录节点,方便后续使用            l1 = l1.next;            l2 = l2.next;        //2、处理链表21长的情况        if l2 != None:            pre.next = l2;//让链表1最后一个非空节点指向链表2的后续节点            l1 = pre.next;//统一l1指针的位置        //3、处理没有被计算过的节点        while l1 != None:            if carry == 1:                if l1.val == 9:                    l1.val = 0;                    carry = 1;                else:                    l1.val += 1;                    carry = 0;            pre = l1;//记录前一个指针,方便后续使用            l1 = l1.next;        /*         * 4、运行到这里表示链表已经没有节点没被处理过了,         * 但是可能存在最后的运算中有进位的情况,         * 这时新增一个链表节点,存储进位值。         * 如[1,9]+[2,1]=[3,0,1]        */        if carry == 1:            pre.next = ListNode(1);        return tmp1;

leetcode上的执行时间是128ms,击败99%+。

水平有限,欢迎指正~
如需转发,请注明出处,thx~

0 0
原创粉丝点击