zoukankan      html  css  js  c++  java
  • Add Two Numbers ,使用链表参数

    # 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):
            l3 = ListNode(0)
            current = l3
            carry = 0
            while l1 or l2: # 1,1 | None,1 | 1,None
                # Pad 0 if None
                if l1 is None:
                    l1v = 0
                else:
                    l1v = l1.val
                if l2 is None:
                    l2v = 0
                else:
                    l2v = l2.val
                # Sum
                tmp = l1v + l2v + carry
                if tmp >= 10:
                    x = tmp%10
                    carry = int(tmp/10)
                else:
                    x = tmp
                    carry = 0
                # Assign value
                current.next = ListNode(x)
                current = current.next
                if l1 is not None:
                    l1 = l1.next
                if l2 is not None:
                    l2 = l2.next
            if carry != 0:
                current.next = ListNode(carry)
            return l3.next
    
    node1=ListNode(1)
    node2=ListNode(2)
    node3=ListNode(3)
    
    node1.next=node2
    node2.next=node3
    
    node4=ListNode(4)
    node5=ListNode(5)
    node6=ListNode(6)
    
    node4.next=node5
    node5.next=node6
    
    x=Solution()
    print(x.addTwoNumbers(node1,node4).val)
    print(x.addTwoNumbers(node1,node4).next.val)
    print(x.addTwoNumbers(node1,node4).next.next.val)

    输出

    5
    7
    9
  • 相关阅读:
    正则表达式基础以及应用
    日常使用之css篇
    echarts的使用总结
    &#65279导致页面顶部空白一行
    vue.js单页面应用实例
    BFC的外边距折叠
    .net 跳出Frameset框架
    Cache缓存使用
    Kafka集群搭建及安全机制手册
    PHP学习笔记
  • 原文地址:https://www.cnblogs.com/sea-stream/p/10463844.html
Copyright © 2011-2022 走看看