您的位置:首页 > 其它

LeetCode - Partition List

2015-04-03 00:36 295 查看
https://leetcode.com/problems/partition-list/

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
.

这道题还是比较简单的,就是分成两个子list,一个里面的值都小于x,一个里面的值都大于等于x,然后再把两个List连起来,注意,第二个list的最后一个node,它本身的next可能是指向非null节点的,要把它设置成null,不然这个list就有circle了。
public ListNode partition(ListNode head, int x) {
if(head==null || head.next==null) return head;
ListNode dummy1 = new ListNode(0);
ListNode dummy2 = new ListNode(0);
ListNode pre1 = dummy1;
ListNode pre2 = dummy2;
while(head!=null){
if(head.val<x){
pre1.next = head;
pre1 = pre1.next;
}
else{
pre2.next = head;
pre2 = pre2.next;
}
head = head.next;
}
pre1.next = dummy2.next;
pre2.next = null;
return dummy1.next;
}


我看leetcode给的tag里面还有two pointer的解法,应该是一个指针扫描,一个指针前面的node全部是比x小的,然后当遇到比x小的,就把这个节点移到第二个指针所在的位置。因为这里没说不能改变node value,所以直接交换值就可以了。或者delete再insert这个node。这种方法还是比较麻烦的哈,容易错。而且这种方法不能保持原有的顺序了。

Input:{2,3,1}, 2
Output:{1,3,2}
Expected:{1,2,3}
public ListNode partition(ListNode head, int x) {
if(head==null || head.next==null) return head;
ListNode traverse = head;
ListNode less = head;
while(traverse!=null){
if(traverse.val < x){
int tmp = less.val;
less.val = traverse.val;
traverse.val = tmp;
less = less.next;
}
traverse = traverse.next;
}
return head;
}


所以还是第一种方法好哈。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: