LeetCode刷题笔记-2

LeetCode-2.Add Two Numbers (Medium):

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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

我的做法:

对链表的操作一般定义一个头结点,我看书上说初始化、删除、插入等操作都会比较方便,所以代码中定义结果链表l3的时候就初始化一个val=0的头结点,然后返回的时候把头结点去掉,也就是返回head.next.

#!/usr/bin/python
# -*- coding: UTF-8 -*-

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

class Solution:
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        l3 = ListNode(0)
        head = l3
        carry = 0
        
        while l1 != None or l2 != None or carry != 0:
            Sum = carry
            if l1!=None:
                Sum += l1.val
                l1 = l1.next
            if l2!=None:
                Sum += l2.val
                l2 = l2.next
    
            if Sum>9:
                carry = int(Sum/10)
                Sum = Sum%10
            else:
                carry = 0
                
            l3.next = ListNode(Sum)
            l3 = l3.next            
        return head.next

 

你可能感兴趣的:(LeetCode,LeetCode)