2014年9月29日星期一

[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.
思路很简单,就是merge的逆过程,用两个dummy节点来表示小于x和大于等于x的两部分,然后将两部分链接起来,尤其要注意的地方是要显示的将当前链表的尾部指向null以保证安全。
public ListNode partition(ListNode head, int x) {
        if(head == null || head.next == null) {
            return head;
        }
        ListNode dum1 = new ListNode(0);
        ListNode dum2 = new ListNode(0);
        ListNode temp1 = dum1, temp2 = dum2;
        
        while(head != null) {
            if(head.val < x) {
                temp1.next = head;
                temp1 = temp1.next;
                head = head.next;
                temp1.next = null; // safe
            }
            else {
                temp2.next = head;
                temp2 = temp2.next;
                head = head.next;
                temp2.next = null; // safe
            }
        }
        temp1.next = dum2.next;
        
        return dum1.next;
    }

没有评论:

发表评论