我试图解决 CTCI 书中链接列表分区的问题,当我查看 here 中的 python 解决方案时,我不确定我是否完全理解这里的行为。 。
def partition(head, pivot):
a_head, a_tail = None, None
b_head, b_tail = None, None
node = head
while node:
if node.data < pivot:
if a_head:
a_tail.next, a_tail = node, node
else:
a_head, a_tail = node, node
else:
if b_head:
b_tail.next, b_tail = node, node
else:
b_head, b_tail = node, node
node = node.next
a_tail.next = b_head
return a_head
class Node():
def __init__(self, data, next=None):
self.data, self.next = data, next
def __str__(self):
string = str(self.data)
if self.next:
string += ',' + str(self.next)
return string
class Test(unittest.TestCase):
def test_partition(self):
head1 =
Node(7,Node(2,Node(9,Node(1,Node(6,Node(3,Node(8)))))))
head2 = partition(head1, 6)
self.assertEqual(str(head2), "2,1,3,7,9,6,8")
head3 = partition(head2, 7)
self.assertEqual(str(head3), "2,1,3,6,7,9,8")
if __name__ == "__main__":
unittest.main()
我们为什么return a_head
如果仅分配了node
,则在最后第一次点击 else
时的值当其值为 None
时的语句?我打印出了a_head
的值在整个过程中,当 a_tail.next = head
时,它似乎改变了值。 .
我不明白为什么会发生这种情况。我假设设置 a_tail.next = head
仅适用于a_tail
,所以不确定为什么会改变 a_head
值也是如此。
最佳答案
之后
a_head, a_tail = node, node
a_head
和 a_tail
都是对同一对象的引用。所以稍后,当你这样做时
a_tail.next, a_tail = node, node
第一次,这也设置了a_head.next
,因为此时a_head
和a_tail
是同一个对象。
关于python - Python中改变链表分区节点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51469722/