How to delete a node in a Java linked list?

In Java, you can implement a linked list using either the LinkedList class or a custom LinkedList class, and to delete a specific node, you can follow these steps:

  1. Firstly, locate the node that needs to be deleted by traversing the linked list in a loop until the desired node is found.
  2. After finding the node to be deleted, set the next pointer of the previous node of that node to point to the next node of the node to be deleted.
  3. Free up the memory space of the node to be deleted by setting its reference to null.

Here is an example code demonstrating how to remove a node from a linked list.

class Node {
    int data;
    Node next;
    
    public Node(int data) {
        this.data = data;
        this.next = null;
    }
}

class LinkedList {
    Node head;
    
    // 在链表末尾添加节点
    public void add(int data) {
        Node newNode = new Node(data);
        
        if (head == null) {
            head = newNode;
        } else {
            Node current = head;
            while (current.next != null) {
                current = current.next;
            }
            current.next = newNode;
        }
    }
    
    // 删除指定节点
    public void delete(int data) {
        Node current = head;
        Node previous = null;
        
        while (current != null) {
            if (current.data == data) {
                if (previous == null) {
                    // 要删除的节点是头节点
                    head = current.next;
                } else {
                    previous.next = current.next;
                }
                current = null; // 释放内存空间
                return;
            }
            previous = current;
            current = current.next;
        }
    }
    
    // 打印链表
    public void display() {
        Node current = head;
        while (current != null) {
            System.out.print(current.data + " ");
            current = current.next;
        }
        System.out.println();
    }
}

public class Main {
    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        list.add(1);
        list.add(2);
        list.add(3);
        list.display(); // 输出:1 2 3
        
        list.delete(2);
        list.display(); // 输出:1 3
    }
}

In the example code above, a custom LinkedList class is created first, with the Node class representing the nodes of the linked list. In the delete method, two pointers, current and previous, are used to traverse the list and locate the node to be deleted, then the pointer references are modified to delete the node. Finally, current = null is used in the delete method to free up memory space.

bannerAds