Middle-题目62:86. Partition List

原创 2016年05月31日 16:32:35

题目原文:
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的碎碎念:
本题的代码写的很复杂,以后应考虑有没有可以合并的边界情况。

版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs

相关文章推荐

leetcode_86_Partition List

思路: 刚开始试着把所有小于x的结点依次插到前面去,但是因为第一个和最后结点的问题真的把我搞得焦头烂额,后来想想,用我媳妇想到的方法可能更清晰一点,用两个链表分别连接小于和大于等于x 的结点,然后再...

leetcode || 86、Partition List

problem: Given a linked list and a value x, partition it such that all nodes less than x come ...

Leetcode 86. Partition List

Given a linked list and a value x, partition it such that all nodes less than x come before nodes gr...

【一天一道LeetCode】#86. Partition List

一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目...

leetcode[86]:Partition List

Partition ListGiven a linked list and a value x, partition it such that all nodes less than x come b...

LeetCode-86. Partition List (JAVA)分区链表

LeetCode-86. Partition List (JAVA)分区链表

Leetcode 86. Partition List(链表划分)

Partition List(链表划分)

LeetCode题解-86-Partition List

原题 解法1(参考别人,更简洁) 解题思路 将比X小的节点串成一串head1,将剩余的节点串成一串head2,最后将head1->head2 代码 public class ...

86. Partition List

链表分离

leetcode题解-86. Partition List

题目:Given a linked list and a value x, partition it such that all nodes less than x come before nodes...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Middle-题目62:86. Partition List
举报原因:
原因补充:

(最多只允许输入30个字)