Java程式:刪除單鏈表中所有偶數節點


在本文中,我們將學習如何從單鏈表中刪除所有偶數節點。Java程式演示瞭如何建立和管理單鏈表,包括新增節點、刪除偶數值節點和列印連結串列。您將看到如何插入節點、刪除偶數值節點以及顯示剩餘節點。

單鏈表由節點組成,每個節點有兩個部分:一部分儲存資料,另一部分儲存下一個節點的地址。這種設定只允許單向遍歷,因為每個節點都透過單個連線連結到下一個節點。


問題陳述

編寫一個Java程式,從單鏈表中刪除所有偶數節點。

輸入

Original List:
1 2 3 4 5 6

輸出

Original List:
1 2 3 4 5 6
List after deleting even nodes:
1 3 5

從單鏈表中刪除所有偶數節點的步驟

以下是從單鏈表中刪除所有偶數節點的步驟:

  • 首先,我們將建立連結串列,我們將初始化一個空連結串列
  • 新增具有整數值(1, 2, 3, 4, 5, 6)的節點到列表的末尾。
  • 刪除偶數節點,我們將刪除前導偶數,我們檢查並從列表的開頭刪除偶數節點。
  • 透過遍歷剩餘列表並刪除具有偶數值的節點來刪除內部偶數。
  • 列印刪除後列表中剩餘節點的值。

Java程式:刪除單鏈表中所有偶數節點

這是一個從單鏈表中刪除所有偶數節點的Java程式:

public class LinkedList {
    // Node class
    static class Node {
        int data;
        Node next;

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

    Node head;

    // Function to insert a node at the end of the list
    public void insert(int data) {
        Node newNode = new Node(data);
        if (head == null) {
            head = newNode;
        } else {
            Node temp = head;
            while (temp.next != null) {
                temp = temp.next;
            }
            temp.next = newNode;
        }
    }

    // Function to delete all even nodes
    public void deleteEvenNodes() {
        if (head == null) return;

        // Removing even nodes at the beginning
        while (head != null && head.data % 2 == 0) {
            head = head.next;
        }

        // Remove even nodes that are not at the head
        Node current = head;
        while (current != null && current.next != null) {
            if (current.next.data % 2 == 0) {
                current.next = current.next.next;
            } else {
                current = current.next;
            }
        }
    }

    // Function to print the linked list
    public void printList() {
        Node temp = head;
        while (temp != null) {
            System.out.print(temp.data + " ");
            temp = temp.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        list.insert(1);
        list.insert(2);
        list.insert(3);
        list.insert(4);
        list.insert(5);
        list.insert(6);

        System.out.println("Original List:");
        list.printList();

        list.deleteEvenNodes();

        System.out.println("List after deleting even nodes:");
        list.printList();
    }
}

輸出

Original List:
1 2 3 4 5 6 
List after deleting even nodes:
1 3 5 

程式碼解釋

LinkedList類定義了一個連結串列,其中包含插入節點、刪除偶數值節點和列印列表的方法。Node類表示列表中的每個節點,包含整數資料和對下一個節點的引用。insert()方法將新節點新增到列表的末尾。deleteEvenNodes()方法首先刪除開頭的偶數節點,然後迭代列表以刪除任何剩餘的偶數節點。最後,printList()方法輸出列表中節點的值。main方法透過建立列表、插入值、刪除偶數和列印結果來演示這些操作。

更新於:2024年9月18日

瀏覽量:108

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.