python常用算法(链表篇)

链表类

class ListNode:
     def __init__(self, x):
         self.val = x
         self.next = None

两个链表相加

def add_two_nums(l1, l2):
    l = head = ListNode(0)
    carry = 0
    while l1 or l2 or carry:
        v1 = v2 = 0
        if l1:
            v1 = l1.val
            l1 = l1.next
        if l2:
            v2 = l2.val
            l2 = l2.next
        carry, val = divmod(v1+v2+carry, 10)
        l.next = ListNode(val)
        l = l.next
    return head.next

你可能感兴趣的:(python常用算法(链表篇))