public class LinkedList { private ListNode head; private int size;

public LinkedList() {
    head = null;
    size = 0;
}

public boolean insert(int i, int x) {
    if (i < 0 || i > size) {
        return false;
    }

    ListNode newNode = new ListNode(x);
    if (i == 0) {
        newNode.next = head;
        head = newNode;
    } else {
        ListNode prev = getNode(i - 1);
        newNode.next = prev.next;
        prev.next = newNode;
    }

    size++;
    return true;
}

private ListNode getNode(int i) {
    ListNode current = head;
    for (int j = 0; j < i; j++) {
        current = current.next;
    }
    return current;
}

public void printList() {
    ListNode current = head;
    while (current != null) {
        System.out.print(current.val + ' ');
        current = current.next;
    }
    System.out.println();
}

private class ListNode {
    private int val;
    private ListNode next;

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

}

public class Main { public static void main(String[] args) { LinkedList list = new LinkedList(); list.insert(0, 6); list.insert(1, 1); list.insert(2, 2); list.insert(3, 3); list.insert(4, 4); list.insert(5, 5); list.printList(); // Output: 6 1 2 3 4 5 } }

Java 单链表插入元素算法:在第 i 个节点之前插入元素 x

原文地址: https://www.cveoy.top/t/topic/pgVk 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录