【问题标题】:How does this linked list partitioning algorithm work?这个链表分区算法是如何工作的?
【发布时间】:2021-04-11 01:19:11
【问题描述】:

我现在正在阅读Cracking the Coding Interview这本书,它提出了一个链表分区问题:

给定一个链表和一个值 x,围绕一个值 x 划分一个链表,使得所有小于 x 的节点都排在所有大于或等于 x 的节点之前。

假设链表不为空。

The solution 取自 GeeksForGeeks 网站,与 CTCI 书中提供的第二种解决方案相同:

// Function to make a new list  
// (using the existing nodes) and  
// return head of new list.  
static Node partition(Node head, int x)  
{  
    /* Let us initialize start and tail nodes of new list */
    Node tail = head;  
  
    // Now iterate original list and connect nodes  
    Node curr = head;  
    while (curr != null)  
    {  
        Node next = curr.next;  
        if (curr.data < x)  
        {  
            /* Insert node at head. */
            curr.next = head;  
            head = curr;  
        }  
  
        else // Append to the list of greater values  
        {  
            /* Insert node at tail. */
            tail.next = curr;  
            tail = curr;  
        }  
        curr = next;  
    }  
    tail.next = null;  
  
    // The head has changed, so we need  
    // to return it to the user.  
    return head;  
}

我不明白这个解决方案。这个算法是如何工作的?为什么是正确的?

【问题讨论】:

    标签: java linked-list partition correctness


    【解决方案1】:

    试着这样想:

    假设这是我们的链表(0) -&gt; (1) -&gt; (2) -&gt; (-1) -&gt; (1) -&gt; (-5)(显然链表看起来不像,但对于我们的例子来说)

    还有x = 0

    我们这样做next = curr.next 这样我们就不会“丢失”下一个节点

    \我要标记 *head 和 ^tail

    现在我们看 (0) 如果它小于 x 并不重要(bcs 它的头和尾)所以它的指针指向它自己

    [*^(0)<  ] [  (1) -> (2) -> (-1) -> (1) -> (-5) ]
    

    现在我们看 (1) 它也不小于 x 所以 (0) 指向它并且它变成 ^tail

    [ *(0) -&gt; ^(1)&lt; ] [ (2) -&gt; (-1) -&gt; (1) -&gt; (-5) ](附上两个列表,但让我们想象一下它们不是)

    同样的事情发生在 (2) ^tail 上,即 (1) 指向它

    [ *(0) -> (1) -> ^(2)<  ] [  (-1) -> (1) -> (-5) ]
    

    现在我们看 (-1) 但是这次它比 x 小所以它设置为指向 *head 然后设置为 *head

    [ *(-1) -> (0) -> (1) -> ^(2)<  ] [  (1) -> (-5) ]
    

    等等:

    [ *(-1) -> (0) -> (1) -> (2) -> ^(1)<  ] [ (-5) ]
    
    [ *(-5) -> (-1) -> (0) -> (1) -> (2) -> ^(1)<  ] [ ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-07
      • 2018-04-03
      • 2021-10-02
      • 1970-01-01
      • 1970-01-01
      • 2014-07-07
      • 2019-12-18
      • 1970-01-01
      相关资源
      最近更新 更多