题解 | #链表分割#

链表分割

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

import java.util.*;
public class Partition {
    public ListNode partition(ListNode head, int x) {
      //根据x,将链表中的数据划分成两部分
      //小于x的部分
        ListNode bs=null;
        ListNode be=null;
      //大于x的部分
        ListNode as=null;
        ListNode ae=null;
        while(head!=null){
          //判断当前head的val是哪一部分
            if(head.val<x){
              //判断是否是第一次插入
                if(bs==null){
                    bs=head;
                    be=head;
                }else{
                    be.next=head;
                    be=be.next;
                }
                head=head.next;
            }else{
                if(as==null){
                    as=head;
                    ae=head;
                }else{
                    ae.next=head;
                    ae=ae.next;
                }
                head=head.next;
            }
        }
      //链表数据全部大于x
        if(bs==null){
            return as;
        }
        if(as!=null){
            ae.next=null;
        }
        be.next=as;
        return bs;
    }
}
全部评论

相关推荐

06-25 21:00
门头沟学院 Java
多拆解背记一下当前的高频场景面试题,结合自己的项目经历去作答,面试通过率原来真的不会低!
牛客96559368...:小公司不就是这样的吗,面试要么是点击就送,要么就是往死里拷打,没有一个统一的标准。这个不能代表所有公司
点赞 评论 收藏
分享
Ncsbbss:又想干活又想要工资,怎么什么好事都让你占了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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