在提供的源代码中,head.next = head.next 的使用什么都不做,也不会改变head 节点的值。
要修改链表中第一个节点的值,先插入一个新节点,需要更新head变量。
解决方案 1 - 将 head 分配为 insert_before() 函数的返回值。
变量previous用于修改节点的前后时间
= None,必须修改第一个节点。
def insert_before(head,data,location):
current = head
previous = None
found = False
while not found:
if (current != None):
if (current.data == location):
new_node = Node(data)
if (previous != None):
new_node.next = previous.next
previous.next = new_node
else:
new_node.next = head
head = new_node
found = True
else:
previous = current
current = current.next
else:
print('location ',location,' not found.')
break
return head
函数的使用变成:
myhead = Node(5)
print(myhead.data) # >> 5
myhead = insert_before(myhead,3,5)
print(myhead.data) # >> 3
print(myhead.next.data) # >> 5
解决方案 2 - 通过在 Node 类中添加 headattribute 来使用 Python 的 OOP。
OOP 方法非常相似,但不是存储head
函数外的节点,函数insert_before()被添加到
班级Node。
第 1 步 - 在类 Node 中添加属性 head。
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
self.head = self # store the first node
第 2 步 - 使用内部 self.head 而不是 head 作为参数
在这种情况下,当新节点应插入到第一个节点之前
节点,赋值很简单self.head = new_node。
def Insert_Before(self,data,location):
current = self.head
previous = None
found = False
print('insert ',data,' before ',location)
while not found:
if (current != None):
if (current.data == location):
new_node = Node(data)
if (previous != None):
new_node.next = previous.next
previous.next = new_node
else:
new_node.next = self.head
self.head = new_node # update the first node
found = True
else:
previous = current
current = current.next
else:
print('location ',location,' not found.')
break
return
函数的使用变成:
myhead = Node(5)
print(myhead.data)
myhead.insert_before(3,5)
print(myhead.head.data)
print(myhead.head.next.data)
警告:不要使用myhead 作为第一个节点,而是使用
myhead.head 属性。