如何修改我的代码来解决LeetCode上的问题2?

huangapple go评论99阅读模式
英文:

How can I modify my code to solve Problem 2 on LeetCode?

问题

LeetCode的问题2提供了两个链接列表。这些链接列表的数字顺序相反,用户必须将两个值的总和作为链接列表返回。

我的解决方案可能不是最有效的,但我想弄清楚如何修改它以增进我对链接列表和树的理解。

我初始化了字符串以保存每个链接列表的数字,然后根据反转后的两个字符串计算总和。

然后,我会将总和的数字插入到一个列表中,并开始逐个弹出最后一个值,将弹出的值添加到新的链接列表中,直到列表为空。

然而,当我创建名为'res'的链接列表时,初始值被初始化为0。有人可以建议我对克服这个特定问题进行的修改吗?

LeetCode问题2

英文:

Problem 2 of LeetCode provides the user with two linked lists. The digits of the linked lists are in reverse order, and the user must return the sum of the two values as a linked list.

My solution may not be the most efficient, but I want to figure out how to modify it for my own understanding of linked lists and trees.

I initialized strings to hold the digits of each linked list, then calculated the total based on both strings reversed.

I would then insert the digits of the sum into a list, and start popping the last value one at a time, adding the popped value to a new linked list until the list is empty.

However when I create my linked list called 'res', the initial value is initialized as 0. Can someone suggest a revision I can make to overcome this particular issue?

Problem 2 of LeetCode

  1. # Definition for singly-linked list.
  2. # class ListNode(object):
  3. # def __init__(self, val=0, next=None):
  4. # self.val = val
  5. # self.next = next
  6. class Solution(object):
  7. def addTwoNumbers(self, l1, l2):
  8. """
  9. :type l1: ListNode
  10. :type l2: ListNode
  11. :rtype: ListNode
  12. """
  13. v1 = ""
  14. v2 = ""
  15. temp = []
  16. while l1 and l2:
  17. v1 += str(l1.val)
  18. v2 += str(l2.val)
  19. l1 = l1.next
  20. l2 = l2.next
  21. v1 = v1[::-1]
  22. v2 = v2[::-1]
  23. total = int(v1) + int(v2)
  24. for char in str(total)[::-1]:
  25. temp.append(char)
  26. res = ListNode()
  27. curr = res
  28. while temp:
  29. curr.next = ListNode(temp.pop(0))
  30. curr = curr.next
  31. return res

答案1

得分: 0

以下是翻译好的部分:

这是如何将值列表转换为链表的方法:

  1. temp = [1, 2, 3, 4]
  2. curr = None # 我们的链表从空开始,表示没有节点
  3. for item in temp:
  4. curr = ListNode(item, curr) # 我们创建一个新节点,它指向当前节点,然后
  5. # 重定向我们的局部引用以指向该节点
  6. # 请记住,右边的计算先进行
  7. # 这使得操作是安全的

这将使我们得到 4 -> 3 -> 2 -> 1

英文:

Here's how you would take a list of values and turn them into a linked list

  1. temp = [1, 2, 3, 4]
  2. curr = None # Our lists start as empty, which is indicated by the absence of a node
  3. for item in temp:
  4. curr = ListNode(item, curr) # We create a new node that points to our current node, then
  5. # redirect our local reference to point to that node
  6. # Remember that the right hand side is calculated first
  7. # which makes this safe

This would leave us with 4 -> 3 -> 2 -> 1

huangapple
  • 本文由 发表于 2023年5月25日 02:25:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76326428.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定