Add two numbers

25 年 6 月 29 日 星期日
172 字
1 分钟

problem

Silly Solution:

python
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        pre1, cur1 = None, l1
        pre2, cur2 = None, l2
        while cur1:
            tmp = cur1.next
            cur1.next = pre1
            pre1 = cur1
            cur1 = tmp
        head1 = pre1
        while cur2:
            tmp = cur2.next
            cur2.next = pre2
            pre2 = cur2
            cur2 = tmp
        head2 = pre2
        n1 = ''
        n2 = ''
        while head1:
            n1 += str(head1.val)
            head1 = head1.next
        while head2:
            n2 += str(head2.val)
            head2 = head2.next
        r = reversed(str(int(n1) + int(n2)))
        # head insertion
        dummy = ListNode()
        cur = dummy
        for i in r:
            node = ListNode(int(i))
            cur.next = node
            cur = node
        return dummy.next

There is one thing need to be noticed:

Head insertion:

python
  # 初始化头节点
  head = ListNode(arr[0])
  current = head

  # 逐个创建后续节点
  for value in arr[1:]:
      node = ListNode(value)
      current.next = node
      current = node

  return head

文章标题:Add two numbers

文章作者:Sirui Chen

文章链接:https://blog.siruichen.me/posts/2add_two_numbers[复制]

最后修改时间:


商业转载请联系站长获得授权,非商业转载请注明本文出处及文章链接,您可以自由地在任何媒体以任何形式复制和分发作品,也可以修改和创作,但是分发衍生作品时必须采用相同的许可协议。
本文采用CC BY-NC-SA 4.0进行许可。