将列表转换为 ListNode

hag*_*n18 3 python int linked-list list

我正在回答有关 LeetCode 的问题,但我很难理解如何在 Python 中编写 LinkedList(或 ListNodes)。我理解 LinkedList 的概念,但我仍然无法理解如何将整数列表转换为相同的 LinkedList!

我已经尝试在线阅读有关这些内容的一些信息,并且我看到有一些可用的递归选项,但是递归非常昂贵,而且我不是它的忠实粉丝。下面是 LeetCode 对 LinkedList 的实现以及我将列表转换为 LinkedList 的方法

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

list1 = [4,5,1,2,0,4]
head = ListNode(list1[0])
e = 1
while e < len(list1):
      print(head)
      head.next = ListNode(list1[e])
      head = head.next
      e+=1
return head
Run Code Online (Sandbox Code Playgroud)

jde*_*esa 5

问题是您缺少对列表头部的引用,因为您正在覆盖它。从这个开始:

list1 = [4,5,1,2,0,4]
head = ListNode(list1[0])
tail = head
Run Code Online (Sandbox Code Playgroud)

然后tail将是对链表最后一个元素的引用。现在在你的循环中你做:

while e < len(list1):
      print(head)
      tail.next = ListNode(list1[e])
      tail = tail.next
      e+=1
Run Code Online (Sandbox Code Playgroud)

所以你像以前一样向列表中添加一个元素,但现在我们正在修改tail变量。在末尾:

return head
Run Code Online (Sandbox Code Playgroud)

您现在将返回列表的头节点。