题解 | 链表分割

链表分割

https://www.nowcoder.com/practice/0e27e0b064de4eacac178676ef9c9d70

import java.util.*;

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Partition {
    public ListNode partition(ListNode pHead, int x) {
        ListNode newhead = new ListNode(0);//创建头节点
        newhead.next=pHead;
        ListNode low = newhead;
        ListNode big = newhead;
        while(big!=null && big.next!=null){
            if(big.next.val <x ){
                if(big==low){
                    big=big.next;
                    low=low.next;
                }
                else {
                    ListNode cur = big.next;//保存要移动的节点
                    big.next = big.next.next;//将该节点移出
                    //将该节点插入
                    cur.next = low.next;
                    low.next = cur;
                    low = low.next; //将小节点更新
                }
            }
            else{
                big = big.next;
            }
        }
        return newhead.next;
    }
}

全部评论

相关推荐

自由水:笑死了,敢这么面试不敢让别人说
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务