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.

链接: http://leetcode.com/problems/partition-list/

题解:

创建两个新链表,每次当前节点值比x小的放入headA,其余放入headB,最后把两个链表接起来。 要注意把右侧链表的下一节点设置为null。

Time Complexity - O(n), Space Complexity - O(n)

public class Solution {

    public ListNode partition(ListNode head, int x) {

        if(head == null || head.next == null)

            return head;

        ListNode headLeft = new ListNode(-1);

        ListNode headRight = new ListNode(-1);

        ListNode nodeLeft = headLeft;

        ListNode nodeRight = headRight;

        

        while(head != null){

            if(head.val < x){

                nodeLeft.next = head;

                nodeLeft = nodeLeft.next;

            } else {

                nodeRight.next = head;

                nodeRight = nodeRight.next;

            }

                

            head = head.next;

        }

        

        nodeRight.next = null;

        nodeLeft.next = headRight.next;

        return headLeft.next;

    }

}

 

测试:

Reference:  http://www.cnblogs.com/springfor/p/3862392.html

你可能感兴趣的:(partition)