算法通关村第一关——链表青铜挑战笔记(单链表)

创建链表

在LeeCode中一般这样创建链表

public class ListNode{
    public int data;
    public ListNode next;
    
    public ListNode(int data){
        this.data = data;
        next = null;
    }
}

遍历链表

要注意创建一个变量来遍历,不要把head丢掉了

public static int getListLength(ListNode head){
    int len = 0;
    ListNode cur = head;
    while(cur != null){
        len++;
        cur = cur.next;
    }
    return len;
}

插入链表节点

count < position - 1可以方便操作,还能防止下标越界(cur为null)

public static ListNode insertNode(ListNode head, ListNode newNode, int position){
    if(head == null){
        return newNode;
    }
    //越界判断
    int size = getLength(head);
    if(position > size + 1 || position < 1){
        System.out.println("位置参数越界");
        return head;
    }
    //表头插入
    if(position == 1){
        newNode.next = head;
        head = newNode;
        return head;
    }
    //表中插入&表尾插入
    ListNode cur = head;
    int count = 1;
    while(count < position - 1){
        cur = cur.next;
        count++;
    }
    newNode.next = cur.next;
    cur.next = newNode;
    return head;
}

删除链表节点

    public static ListNode deleteNode(ListNode head, int position){
        if(head == null){
            return null;
        }
        //越界判断
        int size = getLength(head);
        //注意position > size与插入链表节点有所区别
        if(position > size || position < 1){
            System.out.println("位置参数越界");
            return head;
        }
        //表头删除
        if(position == 1){
            return head.next;
        }
        //表中删除&表尾删除
        ListNode cur = head;
        int count = 1;
        while(count < position - 1){
            cur = cur.next;
            count++;
        }
        cur.next = cur.next.next;
        return head;
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值