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; }
* }
*/
class Solution {
public ListNode partition(ListNode head, int x) {
if (head==null || head.next==null) {
return head;
}
ListNode s = new ListNode(0);//small partition
ListNode p = s;
ListNode l = new ListNode(0);//large partition
ListNode q = l;
while(head!=null){
if (head.val<x) {
p.next = head;
p = p.next;
}else {
q.next = head;
q = q.next;
}
head = head.next;
}
q.next = null;
p.next = l.next;
return