编程导航算法通关村第一关|青铜学习

单向链表

单向链表节点的定义

public class Node {
   public int val;
   public Node next;
   public Node(int val){
       this.val=val;
       next=null;
   }
}

1.JAVA如何构造单向链表

一般Node定义一个节点,一个节点有一个值val,一个指向下一个节点的指针next 

构建链表:Node的指针next指向下一个Node

2.如何获取链表的长度

 public int getLengthNode(Node head){
        int count =0;
        Node node = head;//头节点head
        while (node!=null){
            count++;
            node=node.next;
        }
        return count;
    }

 3.链表的插入

 public static Node insertNode(Node head,Node nodeInsert,int position){
       //nodeInsert是头节点,无法进行插入
       if (head==null){
           return nodeInsert;
       }
       //获取链表的存放节点数
       int size = getLengthNode(head);
       //判断参数是否合法
       if (position<1 || position >size +1){
           return head;
       }
       //头节点插入
       if (position==1){
           head=nodeInsert;
           return head;
       }
       //除头结点插入的其他情况
       Node pNode=head;
       int count = 1 ;
       while (count < position -1){
           count++;
           pNode=pNode.next;
       }
       //坑
       nodeInsert.next=pNode.next;
       pNode.next=nodeInsert;
       return head;
   }

4.链表的删除

 /**
     * 删除链表中的元素
     * @param head 链表
     * @param position 要删除的节点位置
     * @return 删除后的新链表
     */
   public Node deleteNode(Node head,int position){
       if (head==null){
           return null;
       }
       int size = getLengthNode(head);
       if (position<1 || position >size){
           System.out.println("参数不合法");
           return head;
       }
       //删除表头节点
       if (position == 1){
           head=head.next;
           return head;
       }else {
           Node preNode = head;
           int count = 1;
           while (count<position-1){
               preNode=preNode.next;
               count++;
           }
           //curNode要删除的节点
           Node curNode=preNode.next;
           preNode.next=curNode.next;
       }
       return head;
   }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值