我正在尝试在 Python 中定义一个链表,但为什么它总是要添加第一个元素


class Node:
def __init__(self, data):
self.key = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
L1 = LinkedList()
print(L1.head)
def Insert(key,root):
temp = root
if (root != None):
while(temp.next):
temp = temp.next
temp.next = Node(key)
print("donr next")
else:
root = Node(key)
print("doneroot")
list1 = [1,2,3,4,5,6]
for i in range(0,len(list1)):
Insert(list1[i],L1.head)
def printing(ll):
temp = ll.head
print("printing")
print(temp)
while(temp):
print(temp.key)
temp = temp.next
printing(L1)

输出是:

无 doneroot doneroot doneroot doneroot doneroot

doneroot




print none

为什么它总是添加到根元素中

在 Python 中,一切都通过引用传递。当传递的对象不可变时,标签实际上会在其范围内重新分配。例如:

def modify_a_list(x):  # lists are mutable
x.append(1)
def modify_a_string(x):  # strings are immutable
x += 'bar'
a = [3,2]
modify_a_list(a)
print(a)  # gives [3, 2, 1]
b = 'text'
modify_a_string(b)
print(b)  # prints 'text' and not 'textbar'.

在您的示例中,当您将L1.head作为参数传递时,它会解析为None,并且方法中名为root的新定义label | variable会重新分配给新Node。但是您希望将其分配给链表的属性head。这可以通过将链表作为参数传递来解决。

class Node:
def __init__(self, data):
self.key = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
L1 = LinkedList()
print(L1.head)
def Insert(key, ll):
temp = ll.head
if ll.head is not None:
while temp.next:
temp = temp.next
temp.next = Node(key)
print("donr next")
else:
ll.head = Node(key)
print("doneroot")
list1 = [1,2,3,4,5,6]
for i in range(0,len(list1)):
Insert(list1[i], L1)
def printing(ll):
temp = ll.head
print("printing")
print(temp)
while temp:
print(temp.key)
temp = temp.next
printing(L1)

相关内容

  • 没有找到相关文章