• LeetCode(2)Add Two Numbers


    题目如下:

    Python代码:

    # Definition for singly-linked list.
    class ListNode(object):
        def __init__(self, x):
            self.val = x
            self.next = None
    
    class Solution(object):
        def addTwoNumbers(self, l1, l2):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """
            head = ListNode(1)
            current = ListNode(1)
            head.next = current
            flag = 0
            while l1!=None and l2!=None:
                sum = l1.val+l2.val+flag
                if sum<10:
                    flag = 0
                    current.next = ListNode(sum)
                else:
                    flag = 1
                    current.next = ListNode(sum-10)
                current = current.next
                l1 = l1.next
                l2 = l2.next
            if l1==None and l2!=None:
                print "in"
                while l2!=None:
                    if flag==0:
                        current.next = ListNode(l2.val)
                    else:
                        if l2.val+1<10:
                            flag = 0
                            current.next = ListNode(l2.val+1)
                        else:
                            flag = 1
                            current.next = ListNode(l2.val-9)
                    l2 = l2.next
                    current = current.next
            if l1!=None and l2==None:
                print "out"
                while l1!=None:
                    if flag==0:
                        current.next = ListNode(l1.val)
                    else:
                        if l1.val+1<10:
                            flag = 0
                            current.next = ListNode(l1.val+1)
                        else:
                            flag = 1
                            current.next = ListNode(l1.val-9)
                    l1 = l1.next
                    current=current.next
            if flag == 1:
                current.next = ListNode(1)
            return head.next.next
    a = ListNode(1)
    b = ListNode(9)
    b.next = ListNode(9)
    c = Solution()
    c.addTwoNumbers(a,b)
  • 相关阅读:
    正则表达式口诀
    Ajax请求的四种方式
    jQuery插件 -- jQuery UI插件
    电脑操作技巧
    递归
    声纹识别环境初次搭建
    视频编码book_实战_全角度——1
    SDK等阅读笔记
    音视频bug调试
    音视频开发进阶指南(二)
  • 原文地址:https://www.cnblogs.com/CQUTWH/p/5934608.html
Copyright © 2020-2023  润新知