单链表插入,删除节点

单链表插入,删除节点
public class 链表插入和删除节点 {
    
    
    public static void main(String[] args) {
    
    
        List<Node> list = new LinkedList<>();
        for (int i = 0; i < 10; i++) {
    
    
            Node node = new Node(i + 1);
            list.add(node);
        }
        Node head = new Node(0);
        head.next = null;
        for (int i = 0; i < 10; i++) {
    
    
            list.get(i).next = head.next; // 头插法
            head.next = list.get(i);
        }
        Node mid = new Node(11);
        //Node dummy = insert(head, mid, 2);
        Node dummy = remove(head, 2);
        while (dummy.next != null) {
    
    
            dummy = dummy.next;
            System.out.println(dummy.value);
        }


    }
    public static Node insert(Node head, Node mid, int index) {
    
    
        int curr = 1;
        Node dummy = head;
        while (curr <= index) {
    
    
            head = head.next;
            curr += 1;
        }
        // 插入节点
        mid.next = head.next;
        head.next = mid;
        return dummy;
    }
    public static Node remove(Node head, int x) {
    
    
        int curr = 1;
        Node dummy = head;
        while (curr < x) {
    
    
            head = head.next;
            curr += 1;
        }
        // 删除节点
        head.next = head.next.next;
        return dummy;
    }

}

猜你喜欢

转载自blog.csdn.net/qq_35712788/article/details/104607568
今日推荐