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

55 阅读1分钟

如何构造出链表

定义: 链表是一种递归的数据结构。它或者为空(null),或者是指向一个节点(node)的引用,该节点含有一个泛型元素和另一个指向另一条链表的引用。

头节点: 对于单链表来说,第一个节点一般称为头节点。知道了头节点,便可以遍历整个链表。

创建链表:

public class Node {
        public int a;//当前节点的值
        public Node next;//指向下一个节点

        Node(int x) {
            a = x;
            next = null;
        }
}
    
ListNode listnode = new ListNode(1);

创建1个节点:

截屏2023-10-26 17.28.55.png

Node first = new Node(1)
first.next = null
head = first

创建2个节点:

截屏2023-10-26 17.33.44.png

Node second = new Node(2)  
first.next = second
second.next = null

创建3个节点:

截屏2023-10-26 17.34.11.png

Node third = new Node(3)  
second.next = third
third.next = null

链表增加元素

在链表的表头插入一个元素:

截屏2023-10-28 20.47.34.png

newNode.next = head 
head = newNode

注意: 如果head为null,则代表此表中没有节点,那么head = newNode。当position<1时,位置越界。

在链表中间插入一个元素:

找到要插入位置的前驱节点

image.png

newNode.next = head.next  
head.next = newNode

注: 顺序不能颠倒。

在单链表的结尾插入一个元素

截屏2023-10-28 21.35.34.png

third.next = newNode  
newNode.next = null

注意: 当position>size+1,位置越界。

链表删除元素

删除头节点:

截屏2023-10-28 21.35.49.png

head = head.next

注: 如果head为null,则head=null。当position<1时,位置越界。

删除尾节点:

找到尾节点的前驱节点

截屏2023-10-28 21.36.03.png

second.next = null

注: 当position>size时,位置越界。

删除中间节点:

找到要删除节点的前驱节点

截屏2023-10-28 21.36.16.png

head.next = head.next.next