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
.
【3.对于涉及head
节点的操作,不如ListNode *dummy = new ListNode(0); dummy->next = head;
;使针对head
节点的处理与其他节点一致。最后返回dummy->next
作为头指针即可。】
思路:制造两个dummy node,消除头结点的额外操作。
public class Solution {
public ListNode partition(ListNode head, int x) {
if(head==null)
return null;
ListNode dummy1=new ListNode(0);//dummy doesnt connect to org list,no need "dummy1.next=head"
ListNode dummy2=new ListNode(0);
ListNode cur=head;
ListNode cur1=dummy1;
ListNode cur2=dummy2;
while(cur!=null){
if(cur.val<x){
cur1.next=cur;
cur1=cur;
}
else{
cur2.next=cur;
cur2=cur;
}
cur=cur.next;
}//end while
cur1.next=dummy2.next;
cur2.next=null;//w/o it, case {2,1},2 will time out cuz cycle list
return dummy1.next;
}
}
双指针解法没看懂。。
http://blog.csdn.net/linhuanmars/article/details/24446871
附:之前做CC150时候的原始方法,定义两组头尾引用。缺点在于head是否为空要单独划分出情况。
public class Solution {
public ListNode partition(ListNode head, int x) {
if(head==null)
return null;
ListNode head1=null;
ListNode tail1=null;
ListNode head2=null;
ListNode tail2=null;
ListNode cur=head;
while(cur!=null){
if(cur.val<x){
if(head1==null){
head1=cur;
tail1=cur;
}
else{
tail1.next=cur;
tail1=cur;
}
}
else{
if(head2==null){
head2=cur;
tail2=cur;
}
else{
tail2.next=cur;
tail2=cur;
}
}
cur=cur.next;
}
if(head1==null)
return head2;
if(head2==null)
return head1;
if(head1!=null && head2!=null){
tail1.next=head2;
tail2.next=null;//【注意】
}
return head1;
}
}
【注意】没有加这句话,造成了循环链表,{2,1},2的testcase超时。另外注意head1,head2为null的情况。
所以涉及头指针的操作,还是定义dummy node好。
【后记】待验证的真理---如果init值为第一个Node,那么while(curr!=null),;如果init值为第一个Node的preNode,那么while(pre.next!=null)。。。想法come up于遍历全表。