溫馨提示×

listnode java如何實現節點刪除

小樊
101
2024-11-20 09:04:15
欄目: 編程語言

在Java中,我們可以使用鏈表數據結構來實現 ListNode。要實現節點刪除,我們需要遵循以下步驟:

  1. 定義一個 ListNode 類,包含一個整數值和一個指向下一個節點的引用。
  2. 創建一個鏈表類,包含一個頭節點引用,并提供添加、刪除和查找節點的方法。
  3. 實現刪除節點的方法,根據給定的值找到要刪除的節點,并將其從鏈表中移除。

以下是一個簡單的實現:

// 定義 ListNode 類
class ListNode {
    int val;
    ListNode next;

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

// 定義鏈表類
class LinkedList {
    ListNode head;

    // 添加節點到鏈表頭部
    public void add(int val) {
        ListNode newNode = new ListNode(val);
        newNode.next = head;
        head = newNode;
    }

    // 刪除指定值的節點
    public void delete(int val) {
        if (head == null) {
            return;
        }

        // 如果頭節點就是要刪除的節點
        if (head.val == val) {
            head = head.next;
            return;
        }

        ListNode current = head;
        while (current.next != null) {
            if (current.next.val == val) {
                current.next = current.next.next;
                return;
            }
            current = current.next;
        }
    }

    // 查找指定值的節點
    public ListNode find(int val) {
        ListNode current = head;
        while (current != null) {
            if (current.val == val) {
                return current;
            }
            current = current.next;
        }
        return null;
    }
}

使用示例:

public class Main {
    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);

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

        list.delete(2);
        System.out.println("List after deleting 2:");
        printList(list);
    }

    // 打印鏈表
    public static void printList(LinkedList list) {
        ListNode current = list.head;
        while (current != null) {
            System.out.print(current.val + " -> ");
            current = current.next;
        }
        System.out.println("null");
    }
}

輸出:

Original list:
1 -> 2 -> 3 -> 4 -> null
List after deleting 2:
1 -> 3 -> 4 -> null

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女