久久精品人人爽,华人av在线,亚洲性视频网站,欧美专区一二三

java鏈表怎么刪除某一個節點

155次閱讀
沒有評論

共計 1228 個字符,預計需要花費 4 分鐘才能閱讀完成。

在 Java 中,可以使用 LinkedList 類或者自定義鏈表類來實現鏈表,并且刪除某一個節點可以按照以下步驟進行操作:

  1. 首先找到要刪除的節點,可以使用循環遍歷鏈表,直到找到要刪除的節點為止。

  2. 找到要刪除的節點后,將該節點的前一個節點的 next 指針指向要刪除節點的下一個節點。

  3. 釋放要刪除的節點的內存空間,即將該節點的引用置為 null。

下面是一個示例代碼,演示如何刪除鏈表中的某一個節點:

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
    }
}

在上面的示例代碼中,首先創建了一個自定義的 LinkedList 類,其中 Node 類表示鏈表的節點。在 delete 方法中,首先使用兩個指針 current 和 previous 來遍歷鏈表,找到要刪除的節點,然后修改指針的指向來刪除節點。最后,在 delete 方法中使用 current = null 來釋放內存空間。

丸趣 TV 網 – 提供最優質的資源集合!

正文完
 
丸趣
版權聲明:本站原創文章,由 丸趣 2024-01-29發表,共計1228字。
轉載說明:除特殊說明外本站除技術相關以外文章皆由網絡搜集發布,轉載請注明出處。
評論(沒有評論)
主站蜘蛛池模板: 沁阳市| 新沂市| 高碑店市| 洮南市| 长顺县| 井研县| 基隆市| 钦州市| 亳州市| 徐水县| 呈贡县| 当涂县| 托里县| 黄石市| 镇坪县| 滨州市| 吉木乃县| 庐江县| 河池市| 阳高县| 台山市| 锦屏县| 普兰店市| 安阳县| 长垣县| 宁都县| 开平市| 遂川县| 进贤县| 阿鲁科尔沁旗| 崇文区| 怀柔区| 类乌齐县| 酒泉市| 湘阴县| 南昌县| 威信县| 安徽省| 平武县| 东台市| 九龙城区|