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

class LinkedList {
    ListNode head;
    
    public LinkedList() {
        head = null;
    }
    
    // 在第i个节点之前插入元素x
    public boolean insert(int i, int x) {
        if (i < 0) {
            return false;
        }
        
        ListNode newNode = new ListNode(x);
        
        if (i == 0) {
            newNode.next = head;
            head = newNode;
        } else {
            ListNode curr = head;
            int count = 0;
            
            while (curr != null && count < i - 1) {
                curr = curr.next;
                count++;
            }
            
            if (curr == null) {
                return false;
            }
            
            newNode.next = curr.next;
            curr.next = newNode;
        }
        
        return true;
    }
    
    // 将链表转换为字符串形式
    public String toString() {
        StringBuilder sb = new StringBuilder();
        ListNode curr = head;
        
        while (curr != null) {
            sb.append(curr.val).append(' ');
            curr = curr.next;
        }
        
        return sb.toString();
    }
}

public class Main {
    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        list.insert(0, 6);
        list.insert(0, 1);
        list.insert(1, 2);
        list.insert(2, 3);
        list.insert(3, 4);
        list.insert(4, 5);
        
        System.out.println(list.toString());
    }
}
Java单链表插入元素算法:在第i个节点之前插入元素x

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

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