算法训练-链表

单链表的概念

数据结构的基础都是创建+增删改查,通过这几个操作构建算法题

头节点,虚拟节点(dummyNode的val不会被使用,初始化为0或者-1等都是可以的

构造链表

public class ListNode {
    int val;
    ListNode next = null;
    ListNode(int x ){
        val=x;
        next=null;
    }

    public static void main(String[] args) {
        ListNode listNode = new ListNode(2);
        System.out.println(listNode.val);
    }
}

上面为链表的定义

开始构造链表

//    构造链表
    private  ListNode initialListNode(int[] arrays){
//        head需要在循环外层定义 这样return才不会报错
        ListNode head = null;
        ListNode curr = null;
        for(int i=0;i<arrays.length;i++){
            ListNode newListNode = new ListNode(arrays[i]);
            newListNode.next=null;
//            循环条件是i等于0也就是数组开始的时候  并非头节点为null 的时候
//            头节点很快就不为空了
            if (i==0){
                head=newListNode;
                curr=newListNode;
            }else {
                curr.next = newListNode;
                curr=curr.next;
            }
        }
        return head;

}

链表的增删改查

这张图画的一般 不太准确 。主要借鉴思维

数组插入

public  static  int getLength2(Node head){
        int length = 0;
        Node node =head;
        while (node!=null){
            length++;
            node=node.next;
        }
        return length;
}

    public  static  Node myinsertNode(Node head,Node nodeInsert,int position){
        //判断语句后面都要return
        if (head==null){
            return  nodeInsert;
        }
        int size = getLength(head);
        if (position>size+1||position<1){
            System.out.println("位置参数不正确");
            return head;
        }
        if (position==1){
            nodeInsert.next=head;
            head=nodeInsert;
            return head;
        }
        Node pNode =head;
        int count =1;
        while (count<position-1){
            pNode=pNode.next;
            count++;
        }
        nodeInsert.next=pNode.next;
        pNode.next=nodeInsert;
        return head;
        
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值