Sunday, February 9, 2014

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.

Solution:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode partition(ListNode head, int x) {
        ListNode left_head = new ListNode(0);
        ListNode right_head = new ListNode(0);
        ListNode left_tail = left_head;
        ListNode right_tail = right_head;
        while(head != null){
            if(head.val < x){
                left_tail.next = head;
                left_tail = head;
            }
            else{
                right_tail.next = head;
                right_tail = head;
            }
            ListNode temp = head.next;
            head.next = null; // avoid infinite loop
            head = temp;
        }
        left_tail.next = right_head.next;
        return left_head.next;
    }
}

No comments:

Post a Comment