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

[分析] 想到创建两个辅助链表就好办了,small链表存储小于x的节点,large链表存储大于x的节点,最后merge两个链表。

public class Solution {
    public ListNode partition(ListNode head, int x) {
        ListNode small = new ListNode(-1);
        ListNode large = new ListNode(1);
        
        ListNode pSmall = small;
        ListNode pLarge = large;
        ListNode curr = head;
        while (curr != null) {
            if (curr.val < x) {
                pSmall.next = curr;
                pSmall = pSmall.next;
            } else {
                pLarge.next = curr;
                pLarge = pLarge.next;
            }
            curr = curr.next;
        }
        pLarge.next = null;
        pSmall.next = large.next;
        return small.next;
    }
}

猜你喜欢

转载自likesky3.iteye.com/blog/2229241