算法通关村第1关——链表青铜挑战笔记

89 阅读1分钟

编写单位节点

@NoArgsConstructor
@Data
public class Node {
    Integer value;
    Node next;

    public Node(Integer value) {
        this.value = value;
        next = null;
    }
}

初始化链表

public static void main(String[] args) {
    int[] a = {1, 2, 3, 4, 5, 6};
    Node head = initBasicLink(a);
    System.out.println(head);
}
static Node initBasicLink(int[] array) {
    Node head = null, cur = null;
    for (int i = 0; i < array.length; i++) {
        Node node = new Node(array[i]);
        if (i == 0) {
            // 此时为头节点
            head = node;
            cur = node;
        } else {
            cur.next = node;
            cur = node;
        }
    }
    return head;
}

链表的增加

/**
 * 链表插入
 *
 * @param head       链表头节点
 * @param nodeInsert 待插入节点
 * @param position   待插入位置,取值从2开始
 * @return 插入后得到的链表头节点
 */
public static Node insertNode(Node head, Node nodeInsert, int position) {
    // 1. 判断传入链表 head 是否为空
    if (head == null) {
        System.out.println("链表为空!");
        return nodeInsert;
    }
    // 2. 判断插入位置 position 是否越界
    int size = BasicListNode.getLength(head);
    if (position > size + 1 || position < 1) {
        System.out.println("插入位置 position 越界!");
        return head;
    }
    // 3. 如果在表头插入
    if (position == 1) {
        nodeInsert.next = head;
        head = nodeInsert;
        return head;
    }
    // 4. 如果是在中间或结尾插入
    // preNode,为 插入位置节点的前一节点
    Node preNode = head;
    int count = 1;
    while (count < position - 1) {
        count++;
        preNode = preNode.next;
    }
    // 退出while循环时,此时以找到 (position-1) 节点
    nodeInsert.next = preNode.next;
    preNode.next = nodeInsert;
    return head;
}

链表的删除

/**
 * 删除节点
 *
 * @param head     链表头节点
 * @param position 删除节点位置,取值从1开始
 * @return 删除后的链表头节点
 */
public static Node deleteNode(Node head, int position) {
    if (head == null) {
        return null;
    }
    int size = getLength(head);
    //这里是size,而不是size+1,如果是size+1,那么要删除的节点位置position可以等于size+1,不符合
    if (position > size || position < 1) {
        System.out.println("输入的参数有误");
        return head;
    }

    if (position == 1) {
        head = head.next;
    } else {
        Node cur = head;
        int count = 1;
        while (count < position -1) {
            count++;
            cur = cur.next;
        }
        // 退出while循环后,此时以找到了要删除节点的前一节点 cur
        Node curNode = cur.next;
        cur.next = curNode.next;
    }
    return head;
}

查询链表长度

/**
 * 获取链表长度
 *
 * @param head
 * @return
 */
public static int getLength(Node head) {
    int length = 0;
    Node node = head;
    while (node != null) {
        length++;
        // 指向下一个节点,直到 next = null,则退出循环
        node = node.next;
    }
    return length;
}