Lintcode96 Partition List solution題解

【題目描述】


Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

給定一個單鏈表和數值x,劃分鏈表使得所有小於x的節點排在大於等於x的節點之前。

你應該保留兩部分內鏈表節點原有的相對順序。

【題目鏈接】

www.lintcode.com/en/problem/partition-list/

【題目解析】

可將整個鏈表先分離爲兩個小的鏈表。

我們建立less和greater,分別存儲小於x的元素和不小於x的元素。遍歷原鏈表,將其中的元素根據其val分別加入對應的鏈表。最後將less的最後一個元素與greater的鏈表頭相連即可。

需要注意的是,若less鏈表爲空,則應該返回greater鏈表的頭。

【參考答案】

www.jiuzhang.com/solutions/partition-list/



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章