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.

题目大意:给定一个单链表和一个指定值,以指定值划分这个单链表,使得左半部分小于指定值,右半部分大于指定值,要求保持原顺序。

解题思路:首先找到第一个比x值大的元素,记录其前驱节点ptr,然后遍历单链表,大于x的跳过,小于x的接到ptr的后面,然后ptr=ptr.next。

   public ListNode partition(ListNode head, int x) {
        if (head==null||head.next == null) {
            return head;
        }
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode ptr = dummy;
        ListNode pre = dummy;
        while(ptr!=null&&ptr.next!=null&&ptr.next.val<x){
            ptr=ptr.next;
            pre=pre.next;
        }
        while(pre.next!=null){
            ListNode tmp = pre.next;
            if(pre.next.val<x){
                ListNode curr = pre.next;
                pre.next=curr.next;
                curr.next=ptr.next;
                ptr.next=curr;
                ptr=ptr.next;
            }
            pre = tmp;
        }
        return dummy.next;
    }
原文地址:https://www.cnblogs.com/aboutblank/p/4528347.html