leetcode.com问题分区列表:无法理解解决方法

时间:2019-12-25 01:48:39

标签: java

problem是:

  

给出一个链表和一个值 x ,对其进行分区,以使所有小于 x 的节点排在大于或等于 x 。

我无法理解此解决方案:

class Solution {
    public ListNode partition(ListNode head, int x) {

        // before and after are the two pointers used to create the two list
        // before_head and after_head are used to save the heads of the two lists.
        // All of these are initialized with the dummy nodes created.
        ListNode before_head = new ListNode(0);
        ListNode before = before_head;

        ListNode after_head = new ListNode(0);
        ListNode after = after_head;

        while (head != null) {

            // If the original list node is lesser than the given x,
            // assign it to the before list.
            if (head.val < x) {
                before.next = head;
                before = before.next;
            } else {
                // If the original list node is greater or equal to the given x,
                // assign it to the after list.
                after.next = head;
                after = after.next;
            }

            // move ahead in the original list
            head = head.next;
        }

        // Last node of "after" list would also be ending node of the reformed list
        after.next = null;

        // Once all the nodes are correctly assigned to the two lists,
        // combine them to form a single list which would be returned.
        before.next = after_head.next;

        return before_head.next;
    }
}

主要,我对before_headafter_head感到困惑。在我看来before_headafter_head都是值设置为0的节点。before_head.next为什么返回分区链表的头,为什么after_head返回指向“之后”链接列表的标题?在我看来,before_headafter_head被初始化为值为0的节点,与其他节点完全分开。 before_headafter_head如何链接到其余列表?谢谢!

1 个答案:

答案 0 :(得分:0)

before_headafter_head参考标记节点,用于简化while循环中的逻辑。

通常在链接列表中,列表将包含headtail字段,这些字段引用列表的第一个/最后一个节点,或者当列表为空的。

因此,您必须编写这样的代码才能将新节点添加到列表中:

null

如果该列表创建了一个虚拟节点,而在列表为空时同时引用了newNode = ... if (this.head == null) { this.head = newNode; this.tail = newNode; } else { this.tail.next = newNode; this.tail = newNode; } head,那么添加新代码要简单得多:

tail

这种虚拟节点称为sentinel node。如您所见,它使加法逻辑更简单,但使其他逻辑(如迭代)更为复杂,因为从newNode = ... this.tail.next = newNode; this.tail = newNode; 开始的Node链将从哨兵节点开始,然后需要跳过。

在问题代码中,主列表不使用哨兵节点,但是两个之前/之后的列表使用临时哨兵节点来简化循环逻辑。该方法结束时将丢弃哨兵节点本身。