【发布时间】:2020-04-10 22:58:44
【问题描述】:
我很难理解切换指针与实际操作链表中对象的概念。
这是从头开始构建链表的代码
class ListNode:
def __init__(self, val:int, nextNode=None):
self.val = val
self.next = nextNode
class LinkedList:
def __init__(self, val=None):
self.head = None
self.tail = None
def addValue(self, val:int):
if self.head == None:
self.head = self.tail = ListNode(val)
else:
self.tail.next = ListNode(val)
self.tail = self.tail.next
return self.tail
def addMultiple(self, values:list):
for i in values:
self.addValue(i)
def add_to_beginning(self, val):
if self.head == None:
self.head = self.tail = ListNode(val)
else:
self.head = ListNode(val, self.head)
def display(self):
elems = []
curr = self.head
while curr:
elems.append(curr.val)
curr = curr.next
print(elems)
在这里创建一个链表:
l1 = LinkedList()
l1.addMultiple([1,2,3,4,5])
例如,如果我想将第 n 个元素移动到头部,那么我创建了这个函数
class Solution:
def move_n_to_head(self, head, n):
if head == None:
return None
if head.next == None:
return head
temp = None
count = 0
dummy = fast = slow = ListNode(0)
fast.next = head
while fast:
if count == n:
temp = fast.next
fast.next = fast.next.next #why does this line manipuate the head?
break
fast = fast.next #why does this line NOT manipulate the head?
count += 1
slow.next = temp
slow.next.next = head
return dummy.next
一切正常,我得到了我想要的解决方案,但特别是我不明白为什么这条线确实操纵头部?
fast.next = fast.next.next
在第三次迭代中使用上述行后,头部现在变为 [1,2,3,5]
但是,当我遍历列表时,这条线 不 操纵头部?每次迭代后头部仍然是[1,2,3,4,5]?
fast = fast.next
我阅读了关于虚拟节点指针的其他 stackoverflow 解释,这很有帮助,但我仍然不明白。
Explanation about dummy nodes and pointers in linked lists
提前致谢!
【问题讨论】:
标签: python object pointers linked-list nodes