链表

66 阅读1分钟

单向链表

public class ListNode {
    
    public int val;

    public ListNode next;

    public ListNode(int val) {
        this.val = val;
    }
}

一、单向链表的插入

头插、中间插、尾插

public static ListNode insert(ListNode head, ListNode insertNode, int pos) {
    if (head == null) {
        return insertNode;
    }
    if (insertNode == null) {
        return head;
    }
    if (pos == 1) {
        insertNode.next = head;
        return insertNode;
    }
    int length = getListLength(head);
    if (pos > length + 1 || pos < 1) {
        System.out.println("位置不合法!");
        return head;
    }
    int count = 1;
    ListNode node = head;
    while (count < pos - 1) {
        count++;
        node = node.next;
    }
    insertNode.next = node.next;
    node.next = insertNode;
    return head;
}

二、单向链表的删除

头删、中间删、尾删

public static ListNode remove(ListNode head, int pos) {
    if (head == null) {
        return null;
    }
    if (pos == 1) {
        head = head.next;
        return head;
    }
    int length = getListLength(head);
    if (pos > length || pos < 1) {
        System.out.println("位置不合法!");
        return head;
    }
    int count = 1;
    ListNode node = head;
    while (count < pos - 1) {
        count++;
        node = node.next;
    }
    node.next = node.next.next;
    return head;
}

双向链表

public class DoubleListNode {

    public int val;

    public DoubleListNode prev;

    public DoubleListNode next;

    public DoubleListNode(int val) {
        this.val = val;
    }
}

一、双向链表的插入

public static DoubleListNode insert(DoubleListNode head, DoubleListNode insertNode, int pos) {
    if (pos == 1) {
        insertNode.next = head;
        head.prev = insertNode;
        return insertNode;
    }
    int length = getListLength(head);
    if (pos < 1 || pos > length + 1) {
        System.out.println("插入位置不合法");
        return head;
    }
    int count = 1;
    DoubleListNode node = head;
    while (count < pos - 1) {
        count++;
        node = node.next;
    }

    if (pos == length + 1) {
        node.next = insertNode;
        insertNode.next = null;
    } else {
        node.next.prev = insertNode;
        insertNode.next = node.next;
        node.next = insertNode;
    }
    insertNode.prev = node;
    return head;
}

二、双向链表的删除

public static DoubleListNode remove(DoubleListNode head, int pos) {
    if (pos == 1) {
        head = head.next;
        return head;
    }
    int length = getListLength(head);
    if (pos < 1 || pos > length) {
        System.out.println("删除位置不合法");
        return head;
    }
    int count = 1;
    DoubleListNode node = head;
    while (count < pos) {
        count++;
        node = node.next;
    }

    if (pos == length) {
        node.prev.next = null;
    } else {
        node.next.prev = node.prev;
        node.prev.next = node.next;
    }

    return head;
}