数组转化为单向链表再顺序添加

public class SingListNode {
    //链表类
        int val;
        SingListNode next;
        public SingListNode(int val) {
            this.val = val;
        }

}
public class SingListNodeInser {
    SingListNode root ;
    /*
    将数组转化为链表
     */
    public SingListNode arrayToListNode(int[] arr){
        //生成链表的根节点,并将数组的第一个元素的值赋给链表的根节点
        SingListNode root = new SingListNode(arr[0]);
        SingListNode other = root; //other作为临时变量
        for (int i = 1;i<arr.length;i++){ //从1开始遍历数组
            SingListNode temp = new SingListNode(arr[i]);//每循环一次生成一个新的节点
            other.next = temp;  //将other的下一个节点指向生成的新节点
            other = temp;  //other为临时变量,指向当前节点
//            if(i==arr.length-1){
//                temp.next = null;
//            }
        }
       this.root = root;
        return root;
    }

    /*
    将元素插入链表
     */
    public void addnode(SingListNode node){
        SingListNode temp = root;  //临时变量
        if (root.next == null){
            root.next = node;
            System.out.println("到尾了");
            return;
        }
        while (temp.next!=null&&temp.next.val<node.val){
            temp = temp.next;  //往下遍历下一个节点
        }
        if (temp.next == null){//到链表尾
            temp.next = node;
            node.next = null;
        }else {
            node.next = temp.next;
            temp.next = node;
        }
        System.out.println("节点"+node.val+"插入成功");
    }

    /*
    遍历链表
     */
    public void printListNode(){
        SingListNode temp = root;
        while (temp!=null){
            System.out.print(temp.val+" ");
            temp = temp.next;
        }
    }

}
public class test09 {
    public static void main(String[] args) {
        int[] arr = {1,3,5,6,7,8};
        SingListNodeInser singListNodeInser = new SingListNodeInser();
        SingListNode listNode = singListNodeInser.arrayToListNode(arr);
        singListNodeInser.addnode(new SingListNode(8));
        singListNodeInser.addnode(new SingListNode(2));
        singListNodeInser.addnode(new SingListNode(77));
        singListNodeInser.printListNode();
    }
}

结果:
在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值