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.

list的操作题,先从前往后找list中比x大的node,然后在这个node后找比x小的node,把小的node插入到大的node前面。

/**
 * 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) {
        if(head == null || head.next == null) return head;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode slow = dummy;
        
        while(slow.next != null){
            ListNode fast = slow.next;
            if(slow.next.val >= x){
                while(fast.next != null){
                    if(fast.next.val >= x){
                        fast = fast.next;
                    }
                    else{
                        ListNode temp = fast.next;
                        fast.next = fast.next.next;
                        temp.next = slow.next;
                        slow.next = temp;
                        break;
                    }
                }
                slow = slow.next;
            }
            else{
                slow = slow.next;
            }
        }
        return dummy.next;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s