Monday, June 22, 2015

Partition List | Leetcode

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: Iterate through the linked list from beginning to end. Maintain two new linked lists, left and right, and for each element in the given linked list, either append it to left or right. At the end, join left to right to form one single linked list as the answer.
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode partition(ListNode head, int x) {
        ListNode leftHead = null;
        ListNode left = null;
        ListNode rightHead = null;
        ListNode right = null;
        
        while (head != null) {
            if (head.val < x) {
                if (leftHead == null) {
                    leftHead = head;
                } else {
                    left.next = head;
                }
                left = head;
                head = head.next;
                left.next = null;
            } else {
                if (rightHead == null) {
                    rightHead = head;
                } else {
                    right.next = head;
                }
                right = head;
                head = head.next;
                right.next = null;
            }
        }
        
        if (left != null) {
            left.next = rightHead;
            return leftHead;
        }
        return rightHead;
    }
}

No comments: