题解 | 链表分割

链表分割

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 lowh = null;//小头节点
        ListNode lowa = null;//小尾节点
        ListNode bigh = null;//大头节点
        ListNode biga = null;//大尾节点
        while(pHead!=null){
           if(pHead.val < x){
               //如果小头节点为空
               if(lowh == null){
                   lowh = lowa = pHead;
               }
               else{
                   lowa.next = pHead;
                   lowa = lowa.next;
               }
           }
           else{
               //如果大头节点为空
               if(bigh == null){
                   bigh = biga = pHead;
               }else{
                   biga.next = pHead;
                   biga = biga.next; 
               }
           }
           pHead = pHead.next;
        }
        //如果小链表为空
        if(lowh==null){
            return bigh;//返回大链表
        }
        lowa.next=bigh;//将两个链表合并
        //如果大链表不为空
        if(bigh!=null){
            biga.next=null;//将链表尾部的下一个节点置为空
        }
        return lowh;
    }
}

全部评论

相关推荐

重生我想学测开:嵌入式的问题,我准备入行京东外卖了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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