leetcode-2

2. 两数相加

给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。

请你将两个数相加,并以相同形式返回一个表示和的链表。

你可以假设除了数字 0 之外,这两个数都不会以 0 开头。

题目链接:https://leetcode-cn.com/problems/add-two-numbers/

官方题解:两数相加 - 两数相加 - 力扣(LeetCode) (leetcode-cn.com)

解法对比:

```python
class ListNode:
def init(self, val=0, next=None):
self.val = val
self.next = next

class LinkList:
def init(self,val=0):
self.header = None

def createLinkList(self,x_s:list):
    self.header = ListNode(x_s[0])
    p = self.header
    for x in x_s[1:]:
        temp_node = ListNode(x)
        p.next = temp_node
        p = temp_node

def printLinkList(self):
    p = self.header
    while p:
        print(p.val,end=" ")
        p = p.next

class Solution:
def addTwoNumbers(self, l1: LinkList, l2: LinkList) -> ListNode:
resLinkList = ListNode()
l1_p = l1.header
l2_p = l2.header
p = resLinkList
overleaf = 0
while l1_p or l2_p:

        if l1_p and l2_p:
            p.val += (l1_p.val + l2_p.val)
            l1_p = l1_p.next
            l2_p = l2_p.next
        elif l1_p and not l2_p:
            p.val += l1_p.val
            l1_p = l1_p.next
        elif not l1_p and l2_p:
            p.val += l2_p.val
            l2_p = l2_p.next
        if p.val > 9:
            overleaf = 1
            p.val = p.val % 10

        if l1_p != None  or l2_p != None or overleaf :

            t = ListNode()
            t.val = overleaf
            p.next = t
            overleaf = 0
            p = t
            
    return resLinkList
def addTwoNumbers2(self,l1:LinkList,l2:LinkList)->ListNode:
    l1 = l1.header # ListNode
    l2 = l2.header # ListNode
    headerLinkList = ListNode()
    overleaf = 0 # 代表进位
    p = headerLinkList
    cnt = 0
    while l1 or l2:
        n1 = l1.val if l1 else 0
        n2 = l2.val if l2 else 0
        sum = n1+n2+overleaf
        
        if cnt == 0:
            p.val = sum %10
        else:
            p.next = ListNode(sum%10)
            p = p.next

        overleaf = sum // 10
        print(sum,sum%10,overleaf)
        if l1:
            l1 = l1.next
        if l2:
            l2 = l2.next
        cnt += 1
    if overleaf > 0:
        p.next = ListNode(overleaf)
        p = p.next
    return headerLinkList
作者

bd160jbgm

发布于

2021-05-10

更新于

2021-05-13

许可协议