Middle-题目62:86. Partition List

本文介绍了一种链表分隔算法,该算法将小于给定值x的节点置于大于等于x的节点之前,同时保持原有相对顺序不变。通过具体实现案例展示了如何用Java语言解决此类问题。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值