簡體   English   中英

這個鏈表分區算法是如何工作的?

[英]How does this linked list partitioning algorithm work?

我現在正在閱讀《 Cracking the Coding Interview 》一書,它提出了一個鏈表分區問題:

給定一個鏈表和一個值 x,圍繞一個值 x 划分一個鏈表,使得所有小於 x 的節點都在所有大於或等於 x 的節點之前。

假設鏈表不為空。

該解決方案取自 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; }

我不明白這個解決方案。 這個算法是如何工作的? 為什么是正確的?

試着這樣想:

假設這是我們的鏈表(0) -> (1) -> (2) -> (-1) -> (1) -> (-5) (顯然鏈表看起來不像這樣,但對於我們的例子)

x = 0

我們執行next = curr.next這樣我們就不會“丟失”下一個節點

\ 我要標記 *head 和 ^tail

現在我們看 (0) 它是否小於 x 並不重要(bcs 它的頭部和尾部)所以它的指針指向自身

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

現在我們看 (1) 它也不小於 x 所以 (0) 指向它並且它變成 ^tail

[ *(0) -> ^(1)< ] [ (2) -> (-1) -> (1) -> (-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)<  ] [ ]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM