题解 | #链表分割#

链表分割

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;
    }
}
全部评论

相关推荐

asdasdasda...:19岁,不容易啊可能升个本会好点,现在学历歧视太严重了
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-27 15:07
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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