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
.
解题思路:
看到网上的想法是用两个链来保存,一个保存小的一个保存大的,然后最后再合并起来。
我的想法其实也是差不多,不过就是用一条链,如果找到小的就往前插,大的就跳过,其实也是类似于两条链吧。不过明显代码量比网上说的那个多。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode partition(ListNode head, int x) {
ListNode First = new ListNode(0);
First.next = head;
ListNode Small = First;
ListNode p = First;
while(p.next!= null && p.next.val < x)
{
p = p.next;
Small = Small.next;
}
while(p.next != null)
{
if(p.next.val >= x)
p = p.next;
else
{
ListNode q = p.next;
p.next = p.next.next;
q.next = Small.next;
Small.next = q;
Small = Small.next;
}
}
return First.next;
}
}