算法通关村第一关----链表青铜挑战笔记

链表

链式存储结构的线性表(链表)采用了一组地址任意的存储单元存放线性表中的数据元素。链表不会按线性的逻辑顺序来保存数据元素,它需要在每个数据元素里保存一个或两个引用上一个/下一个数据元素的引用(指针)。
单链表节点示意图
双向链表节点示意图

创建链表

public class ListNode{
    public int val;
    public ListNode next;

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

ListNode listNode = new ListNode(1);

单链表的基本操作

1. 遍历操作

只能通过头节点一个一个向后查找

public static int getListNodeLength(ListNode head){
    int length = 0;
    ListNode listnode = head;
    while(listnode != null){
        length++;
        listnode = listnode.next;
    }
    return length;
} 

2. 插入操作

  • 尾部插入
  • 头部插入
  • 中间插入
/**
     *
     * @param head 头节点
     * @param insertNode 待插入节点
     * @param position 待插位置
     * @return 链表
     * @throws Exception
     */
    public static ListNode insertNode(ListNode head, ListNode insertNode, int position) throws Exception{
        if(head == null){
            return insertNode;
        }

        int size = getListNodeLength(head);

        if(size+1 < position || position <1){
            throw new IndexOutOfBoundsException("越界异常");
        }

        //头部插入
        if (position == 1){
            insertNode.next = head;
            head = insertNode;
            return head;
        }

        ListNode pnode = head;
        //指针
        int count = 1;

        //再插入的前一个位置停下来
        while(count<position-1){
            pnode = pnode.next;
            count++;
        }

        insertNode.next = pnode.next;
        pnode.next = insertNode;

        return head;
    }

3. 删除操作

  • 尾部删除
  • 头部删除
  • 中间删除
 /**
     *
     * @param head 头节点
     * @param position 删除位置
     * @return 删除后的链表
     * @throws Exception
     */

    public static ListNode deleteNode(ListNode head, int position) throws Exception{
        if (head == null){
            return null;
        }

        int size = getListNodeLength(head);

        if (position < 1 || position > size){
            throw new IndexOutOfBoundsException("越界");
        }

        if(position == 1){
            return head.next;
        }else{
            ListNode cur = head;
            int count = 1;
            while(count < position-1){
                head = head.next;
                count++;
            }
            cur.next = cur.next.next;
        }
        return head;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值