JAVA——链表分割

问题:现有一链表的头指针 ListNode* pHead,给一定值x,编写一段代码将所有小于x的结点排在其余结点之前,且不能改变原来的数据顺序,返回重新排列后的链表的头指针。

方法:把所有的数分成两组,小于x的一组,大于等于x的一组。小于x的数以bs开头be结尾;大于等于x的数以as开头,ae结尾。若cur=null则循环结束。
之后要判断bs是否为空,以及as是否为空的情况。
在这里插入图片描述

代码:

public ListNode partition(ListNode pHead, int x) {
        // write code here
        ListNode cur=pHead;
        ListNode bs=null;
        ListNode be=null;
        ListNode as=null;
        ListNode ae=null;
        while(cur!=null){
            if(cur.val>=x){
                if(as==null){
                    as=ae=cur;
                }
                else{
                    ae.next=cur;
                    ae=ae.next;
                }
                cur=cur.next;
            }
            else if(cur.val<x){
                if(bs==null){
                    bs=be=cur;
                }
                else{
                    be.next=cur;
                    be=be.next;
                }
                cur=cur.next;
            }
        }
        if(bs==null){
            return as;
        }
        else{
            be.next=as;
            if(as!=null){
               ae.next=null;
            }
            return bs;
        }
    }