python - Python中改变链表分区节点值

标签 python linked-list

我试图解决 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_heada_tail 都是对同一对象的引用。所以稍后,当你这样做时

a_tail.next, a_tail = node, node

第一次,这也设置了a_head.next,因为此时a_heada_tail是同一个对象。

关于python - Python中改变链表分区节点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51469722/

相关文章:

java - 从列表中获取/删除第一个元素的有效方法?

python - 访问 ipdb 中的类成员

python - 连接多个列表

python - Scapy 中 HTTP 连接的低级管理

python - 有人通过 Macports 在 Snow Leopard 中安装了 python26 吗?

python - 如何在没有任何第三方库的情况下比较两个 2-dim 数组的列?

java - 在java中反转并打印单链表

Java:创建 LinkedList 并将其转换为 ArrayList 进行排序是否有意义?

c++ - 链表问题

模仿 vector 的 C++ 链表