英文:
Why is it necessary to take a new variable "head" in for loop?
问题
class Node:
def init(self, data):
self.data = data
self.ref = None
def Print_LL(linkedlist):
if linkedlist is None:
print("链表为空!!")
else:
while linkedlist is not None:
print(linkedlist.data)
linkedlist = linkedlist.ref
def arr_to_LL(arr, n):
linkedlist = None
for i in range(0, n):
new_node = Node(arr[i])
if linkedlist is None:
linkedlist = new_node
else:
head = linkedlist
while head.ref is not None:
head = head.ref
head.ref = new_node
return linkedlist
为什么要使用 "head" 变量?为什么不能继续使用 linkedlist?
英文:
class Node:
def __init__(self, data):
self.data = data
self.ref = None
def Print_LL(linkedlist):
if linkedlist is None:
print("LinkedList is empty!!")
else:
while linkedlist is not None:
print(linkedlist.data)
linkedlist = linkedlist.ref
def arr_to_LL(arr, n):
linkedlist = None
for i in range(0,n):
new_node = Node(arr[i])
if linkedlist is None:
linkedlist = new_node
else:
head = linkedlist
while head.ref is not None:
head = head.ref
head.ref = new_node
return linkedlist
why to take "head" variable? why cant we continue with linkedlist
答案1
得分: 1
linkedlist 是指向链表头部的引用。head,尽管名字是这样,实际上是指向链表末尾,更具体地说是指向要连接新节点的节点。对于 arr_to_LL 更好的定义可能是
def arr_to_LL(arr):
head = None
for v in arr:
new_node = Node(v)
if head is None:
head = new_node
else:
curr.ref = new_node
curr = new_node
return head
这个 for 循环有两个不变点:
head总是指向(可能为空的)链表的前端。curr(一旦定义)总是指向链表的末尾。
当你遍历数组时,你简单地将一个新节点附加到末尾,然后更新末尾。
如果你使用常见的用虚拟节点表示空链表的约定,这变得更简单,因为现在你不需要特殊处理 head is None。
def arr_to_LL(arr):
# 我们将在虚拟节点中存储长度,为什么不呢?
head = curr = Node(0)
for v in arr:
curr.ref = Node(v)
curr = new_node
head.data += 1
return head
英文:
linkedlist is a reference to the head of the list. head, despite the name, is just a reference to the end of the list, or more specifically to the node to which you'll attach a new node. A better definition of arr_to_LL might be
def arr_to_LL(arr):
head = None
for v in arr:
new_node = Node(v)
if head is None:
head = new_node
else:
curr.ref = new_node
curr = new_node
return head
This for loop has two invariants:
headalways refers to the front of the (possibly empty) linked list.curr(once defined) always refers to the end of the linked list.
As you iterate over the array, you simply append a new node to the end, then update the end.
If you use the common convention of an empty linked list represented by a dummy node, it becomes even simpler, as now you don't need a special case for head is None.
def arr_to_LL(arr):
# We'll store the length in the dummy node, because why not?
head = curr = Node(0)
for v in arr:
curr.ref = Node(v)
curr = new_node
head.data += 1
return head
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论