这道题懂得思路是挺容易的,操作上并不难。
新建两条链表,一条存储小于x的结点,另一条存储大于x的结点,遍历原链表把值都接到对应链表上。
然后连接链表的结点,最后返回。

class Solution {
    public ListNode partition(ListNode head, int x) {
        ListNode smallSentinel = new ListNode(0);
        ListNode greatSentinel = new ListNode(0);
        ListNode smallerList = smallSentinel;
        ListNode greaterList = greatSentinel;
        while(head != null){
            ListNode nextNode = head.next;
            // 插入到对应链表的尾部
            if(head.val < x){
                smallerList.next = head;
                smallerList = head;
            }else{
                greaterList.next = head;
                greaterList = head;
            }
            head = nextNode;
        }
        // 连接链表
        smallerList.next = greatSentinel.next;
        greaterList.next = null;
        return smallSentinel.next;
    }
}