LintCode 96.链表划分

描述

给定一个单链表和数值x,划分链表使得所有小于x的节点排在大于等于x的节点之前。

你应该保留两部分内链表节点原有的相对顺序。

 

样例

样例 1:

输入: list = null, x = 0
输出: null	
样例解释: 空链表本身满足要求

样例 2:

输入: list = 1->4->3->2->5->2->null, x = 3
输出: 1->2->2->4->3->5->null	
样例解释: 要保持原有的相对顺序。

代码部分 

/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param head: The first node of linked list
     * @param x: An integer
     * @return: A ListNode
     */
    public ListNode partition(ListNode head, int x) {
        // write your code here
        if(head==null)return null;
        ListNode reslowDummy=new ListNode(0);
        ListNode reshighDummy=new ListNode(0);
        ListNode reslow=reslowDummy;
        ListNode reshigh=reshighDummy;
        while(head!=null){
            if(head.val<x){
                reslowDummy.next=head;
                reslowDummy=head;
            }
            else if(head.val>=x){
                reshighDummy.next=head;
                reshighDummy=head;
            }
            head=head.next;
        }
        //拼接
        if(reshighDummy.val<x){
                reslowDummy.next=null;
        }
        else{
                reshighDummy.next=null;
        }
        reslowDummy.next=reshigh.next;
        return reslow.next;
    }
}

补充说明

 

        if(reshighDummy.val<x){
                reslowDummy.next=null;
        }
        else{
                reshighDummy.next=null;
        }

最后需要给最后节点的下一个节点赋值null!!最开始没有写这段代码,报错java.lang.NullPointerException,需要注意。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值