简体   繁体   English

为什么在划分链表时会进入无限循环?

[英]Why am i entering into an infinite loop when partitioning a linked list?

This is a common problem of partitioning a linked list into two parts.这是将链表分成两部分的常见问题。 The list with nodes smaller than x will come first and the list of nodes larger than x will come after.节点小于 x 的列表将排在前面,节点大于 x 的列表将排在后面。

My question is - why do i need to set after.next to null after creating my two separate linked lists?我的问题是 - 为什么我需要在创建两个单独的链表后将 after.next 设置为 null? Without setting it to null, I enter an infinite loop when trying to print this list.如果不将其设置为 null,我会在尝试打印此列表时进入无限循环。 My debugger shows that before_head.next has a never-ending list of nodes attached to it...我的调试器显示 before_head.next 有一个永无止境的节点列表附加到它......

public Node partition(Node head, int x){
  Node before_head=new Node(0);
  Node before=before_head;
  Node after_head=new Node(0);
  Node after=after_head;

  while(head != null){
    if(head.val < x){
      before.next=head;
      before=before.next;
    else{
      after.next=head;
      after=after.next;
     }
    head=head.next;
   }

   after.next=null;
   before.next=after_head;

   return before_head.next;
}

why do i need to set after.next to null after creating my two separate linked lists?为什么我需要在创建两个单独的链表后将 after.next 设置为 null?

The last node of a linked list doesn't have a next node.链表的最后一个节点没有下一个节点。 In a linked list representation such as yours, that takes the form of the last node's next reference being null.在像您这样的链表表示中,最后一个节点的next引用形式为 null。

You are rearranging the existing nodes of the list by changing their next references.您正在通过更改它们的next引用来重新排列列表的现有节点。 At the end of that process, after is a reference to the last node, therefore its next reference needs to be null. If it was also the last node in the original order then all is well -- its next reference is already null. If after was not the last node in the original order, however, then after.next will refer to one of the other nodes until you set it null. And whatever other node that is, it comes before after in the new order, forming a loop.在该过程结束时, after是对最后一个节点的引用,因此它的next引用需要是 null。如果它也是原始顺序中的最后一个节点,那么一切都很好——它的next引用已经是 null。如果after不是原始顺序中的最后一个节点,但是, after.next将引用其他节点之一,直到您将其设置为 null。无论其他节点是什么,它都会在新顺序中出现在after之前,形成一个循环.


Note also that还要注意的是

 before.next=after_head;

appears to be wrong.似乎是错误的。 after_head is the dummy head node of the second partition, so you do not want to include it in the new list. after_head是第二个分区的虚拟头节点,因此您不想将其包含在新列表中。 I think you want我想你想要

    before.next = after_head.next;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM