链表面试题------Java链表分割

## 题目:编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前

*分析:*

    1>定义两个新链表    small  和  big
     2>遍历原链表,
     将结点值比  x 小的 尾插到  small 上    
    将结点值比  x 大的 尾插到  big 上


class Node{
    int val;
    Node next = null;

    Node(int val){
        this.val = val;
    }

    //打印链表的方法
    @Override
    public String toString() {
        return String.format("Node(%d)",val);
    }
}
public class Practice {

    //把一个链表分为一边比x大一边比x小
    private static Node partition(Node head,int x){
        //定义一个大链表   一个小链表
        Node small = null;
        Node big = null;

        //分别记录  大链表 和 小链表 的最后一个结点
        Node smallLast = null;
        Node bigLast = null;

        Node cur = head;
        //根据结点的值 与 x 的大小关系 将原链表的结点分别尾插到 新的 small链表 和 big 链表上
        while(cur != null){
            if(cur.val < x){
                if(small == null){
                    small = cur;
                }else{
                    smallLast.next = cur;
                }
                smallLast = cur;
            }else{
                if(big == null){
                    big = cur;
                }else{
                    bigLast.next  = cur;
                }
                bigLast = cur;
            }
            cur = cur.next;
        }

        //如果small为空时,直接返回big
        if(small == null){
            return big;
        }else{
            smallLast.next = big;
            //保证最后一个节点为null
            if(big != null){
                bigLast.next = null;
            }

        }
        return small;
    }

    public static Node test(){
        Node n1 = new Node(5);
        Node n2 = new Node(3);
        Node n3 = new Node(6);
        Node n4 = new Node(2);
        Node n5 = new Node(4);
        Node n6 = new Node(1);
        n1.next = n2;
        n2.next = n3;
        n3.next = n4;
        n4.next = n5;
        n5.next = n6;
        return n1;
    }
    public static void main(String[] args) {

        Node head = partition(test(),3);
        for(Node cur = head;cur != null;cur = cur.next){
            System.out.println(cur);
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值