描述:
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 的结点,然后再把两个结点链接到一起,就可以了。在实施的时候稍微偷点懒,首先创建两个头节点,哎,现在终于明白头节点的巨大作用了,其实,按我的那个思路,先搞个头节点,然后再用两个引用pre和cur就可以轻松搞定本题了。
做完本题感觉收获好大,头节点的出现真的让我可以很轻松地搞定许多前面我费了好大的劲才搞定的题目,尤其是涉及到在链表的开始进行插入的题目。
代码:
public ListNode partition(ListNode head, int x) {
if(head==null||head.next==null)
return head;
ListNode little_start=new ListNode(0),little_end=little_start;
ListNode big_start=new ListNode(0),big_end=big_start;
ListNode pListNode=head;
while(pListNode!=null)
{
if(pListNode.val<x)
{
little_end.next=pListNode;
little_end=pListNode;
}else
{
big_end.next=pListNode;
big_end=pListNode;
}
pListNode=pListNode.next;
}
little_start=little_start.next;
big_start=big_start.next;
if(little_start!=null)
{
big_end.next=null;
little_end.next=big_start;
return little_start;
}
else
return big_start;
}