Middle-题目62:86. 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.
题目大意:
给出一个链表和一个值x,把<x的节点都搬到x前面,大于x的节点都搬到x后面,并保持原有的顺序。
题目分析:
类似快排,注意一些边界情况和特殊情况即可。多看看错误的test case,多在纸上画画就好了。
源码:(language:java)

public class Solution {
    public static ListNode partition(ListNode head, int x) {
        if(head == null || head.next == null) return head;
        ListNode beforex = null,afterx = null;
        for(ListNode node = head; node!=null; node=node.next) {
            if(node.val<x) {
                if(beforex == null)
                    beforex = new ListNode(node.val);
                else {
                    ListNode temp = beforex;
                    while(temp.next!=null)
                        temp=temp.next;
                    temp.next=new ListNode(node.val);
                }
            }
            else {
                if(afterx == null)
                    afterx = new ListNode(node.val);
                else {
                    ListNode temp = afterx;
                    while(temp.next!=null)
                        temp=temp.next;
                    temp.next=new ListNode(node.val);
                }
            }
        }
        ListNode temp = beforex;
        if (temp!=null) {
            while(temp.next!=null)
                temp=temp.next;
            temp.next=afterx;
            return beforex;
        }
        else
            return afterx;
    }
}

成绩:
1ms,beats 4.36%,众数1ms,95.64%
cmershen的碎碎念:
本题的代码写的很复杂,以后应考虑有没有可以合并的边界情况。

你可能感兴趣的:(Middle-题目62:86. Partition List)