Partition List leetcode java

愛做飯的小瑩子發表於2014-07-23

題目

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.

For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

 

題解

這道題就是說給定一個x的值,小於x都放在大於等於x的前面,並且不改變連結串列之間node原始的相對位置。每次看這道題我老是繞暈,糾結為什麼4在3的前面。。其實還是得理解題意,4->3->5都是大於等3的數,而且這保持了他們原來的相對位置 。

所以,這道題是不需要任何排序操作的,題解方法很巧妙。

new兩個新連結串列,一個用來建立所有大於等於x的連結串列,一個用來建立所有小於x的連結串列。

遍歷整個連結串列時,噹噹前node的val小於x時,接在小連結串列上,反之,接在大連結串列上。這樣就保證了相對順序沒有改變,而僅僅對連結串列做了與x的比較判斷。

最後,把小連結串列接在大連結串列上,別忘了把大連結串列的結尾賦成null。

 程式碼如下:

 1     public ListNode partition(ListNode head, int x) {
 2         if(head==null||head.next==null)
 3             return head;
 4         
 5         ListNode small = new ListNode(-1);
 6         ListNode newsmallhead = small;
 7         ListNode big = new ListNode(-1);
 8         ListNode newbighead = big;
 9         
10         while(head!=null){
11             if(head.val<x){
12                 small.next = head;
13                 small = small.next;
14             }else{
15                 big.next = head;
16                 big = big.next;
17             }
18             head = head.next;
19         }
20         big.next = null;
21         
22         small.next = newbighead.next;
23         
24         return newsmallhead.next;
25     }

 

 

相關文章