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

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 be = null;
        ListNode ae = null;
        ListNode as = null;
        ListNode bs = null;
        ListNode cur = pHead;
        while(cur != null){
        if(cur.val < x){
            if(bs == null){//小于x的部分一个节点还没有的情况下
                bs = cur;
                be = cur;
            }else{//有了节点
                be.next = cur;
                be = be.next;
            }
        }else{
            if(as == null){//大于x的部分一个节点还没有的情况下
                as = cur;
                ae = cur;
            }else{//小于x的部分一个节点还没有的情况下
                ae.next = cur;
                ae = ae.next;
            }
        }
        cur = cur.next;
        }
        if(bs == null){//如果bs为空,返回的是as
            return as;
        }
        be.next = as;
        if(as != null){//as不为空时,我们要把as的最后一个节点置为空
            ae.next = null;
        }
        return bs;
        // write code here
    }
}
Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐