86. 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.

这道题没看答案之前不明白到底如何移动,看了答案发现太简单了。new两个链表,遍历原链表,把val大于等于x的节点接到big后面,把val小于x的节点接到small后面,最后把big接到small后面,就可以了。

86. Partition List_第1张图片
WechatIMG53.jpeg
/**
 * 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 big = new ListNode(-1);
        ListNode small = new ListNode(-1);
        ListNode bighead = big;
        ListNode smallhead = small;
        while (head != null){
            if (head.val < x){
                smallhead.next = head;
                smallhead = smallhead.next;
            } else {
                bighead.next = head;
                bighead = bighead.next;
            }
            head = head.next;
        }
        bighead.next = null;
        smallhead.next = big.next;
        return small.next;
    }
}

你可能感兴趣的:(86. Partition List)