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

发布时间 2023-09-18 21:28:49作者: leexy316

链表

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

单链表节点示意图双向链表节点示意图

创建链表

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

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

ListNode listNode = new ListNode(1);

单链表的基本操作

遍历操作

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

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

插入操作

  • 尾部插入
  • 头部插入
  • 中间插入
/**
     *
     * @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;
    }

删除操作

  • 尾部删除
  • 头部删除
  • 中间删除
    /**
     *
     * @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;
    }