NC23 划分链表

描述

给出一个链表和一个值,以为参照将链表划分成两部分,使所有小于的节点都位于大于或等于的节点之前。
两个部分之内的节点之间要保持的原始相对顺序。
例如:
给出 
返回 

示例1

输入:

{1,4,3,2,5,2},3

返回值:

{1,2,2,4,3,5}

分析:

1. 循环两遍,第一遍找小于划分元素的节点,第二遍找大于等于划分元素的节点,放到结果链表里。空间复杂度O(n)。

2. 循环一遍,两个指针,一个找小于的元素更改链接到小于元素链表,另一个找大于等于的元素更改链接到大于等于链表,最后两个结果链表连起来。空间复杂度O(1)。

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @param x int整型 
     * @return ListNode类
     */
    public ListNode partition (ListNode head, int x) {
        // write code here
        if(head == null) return head;
        if(head.next == null) return head;
        ListNode tmp = head;
        ListNode res = null;
        ListNode result = res;
        while(tmp != null){
            if(tmp.val < x){
                if(res == null){
                    res = new ListNode(x);
                    result = res;
                }
                else{
                    res.next = new ListNode(x);
                    res = res.next;
                }
                res.val = tmp.val;
            }
                tmp = tmp.next;
        }
        tmp = head;
        while(tmp != null){
            if(tmp.val >= x){
                if(res == null){
                    res = new ListNode(x);
                    result = res;
                }
                else{
                    res.next = new ListNode(x);
                    res = res.next;
                }
                res.val = tmp.val;
            }
                tmp = tmp.next;
        }
        return result;
    }
}

提交结果:答案正确 运行时间:27ms 占用内存:10352KB 使用语言:Java 用例通过率:100.00% 

public class Solution {
    /**
     *
     * @param head ListNode类
     * @param x int整型
     * @return ListNode类
     */
    public ListNode partition (ListNode head, int x) {
        // write code here
        if (head == null) return head;
        ListNode h1 = new ListNode(0);
        ListNode h2 = new ListNode(0);
        ListNode n1 = h1;
        ListNode n2 = h2;
        ListNode tmp = head;
        while (tmp != null) {
            if (tmp.val < x) {
                n1.next = tmp;
                n1 = tmp;
            } else {
                n2.next = tmp;
                n2 = tmp;
            }
            tmp = tmp.next;
        }
        n2.next = null;
        n1.next = h2.next;
        return h1.next;
    }
}

提交结果:答案正确 运行时间:27ms 占用内存:10256KB 使用语言:Java 用例通过率:100.00%

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值