【Leetcode】86. Partition List

Question:

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.

Tips:

给定一个无序的链表,将链表分成两部分,前半部分的val全部小于x;后半部分大于等于x。

前后两部分的结点,相对位置不变,即node1 与node2 均大于x 那么不管node1与node2的val谁大,最终顺序仍未node1->node2.

思路:

初始化两个头结点small 与big,然后开始遍历链表,当head.val>=x ,就将head接到big.next上。否则接到small.next上。

head走到末尾,将small的最后一个结点与big的第一个结点连接,返回small的第一个结点即可。

代码:

 

public ListNode partition(ListNode head, int x) {
        if (head == null)
            return head;
        ListNode big = new ListNode(-1);
        ListNode small = new ListNode(-1);
        ListNode temp = big;// 记录big的第一个结点位置
        ListNode result = small;// 记录small的第一个结点位置
        while (head != null) {
            if (head.val >= x) {
                big.next = head;
                big = big.next;

            } else {
                small.next = head;
                small = small.next;
            }
            head = head.next;
        }
        //small的最后一个结点与big的第一个结点连接
        small.next = temp.next;
        big.next = null;
        return result.next;
    }

 

测试代码:

public static void main(String[] args) {
        L86PartitionList l86 = new L86PartitionList();
        ListNode head1 = new ListNode(1);
        ListNode head2 = new ListNode(4);
        ListNode head3 = new ListNode(2);
        ListNode head4 = new ListNode(5);
        ListNode head5 = new ListNode(3);
        ListNode head6 = new ListNode(6);
        ListNode head7 = null;
        head1.next = head2;
        head2.next = head3;
        head3.next = head4;
        head4.next = head5;
        head5.next = head6;
        head6.next = head7;
        ListNode head = l86.partition(head1, 30);
        while (head != null) {
            System.out.println(head.val);
            head = head.next;
        }
    }

 

posted @ 2018-02-26 11:04  于淼  阅读(128)  评论(0编辑  收藏  举报