溫馨提示×

java怎么實現(xiàn)鏈表結(jié)構(gòu)

小億
84
2023-12-15 02:34:13
欄目: 編程語言

在Java中,可以通過自定義類實現(xiàn)鏈表結(jié)構(gòu)。以下是一個簡單的鏈表實現(xiàn)示例:

public class Node {
    private int data;
    private Node next;

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

    public int getData() {
        return data;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }
}

public class LinkedList {
    private Node head;

    public LinkedList() {
        this.head = null;
    }

    public void add(int data) {
        Node newNode = new Node(data);
        if (head == null) {
            head = newNode;
        } else {
            Node current = head;
            while (current.getNext() != null) {
                current = current.getNext();
            }
            current.setNext(newNode);
        }
    }

    public void print() {
        Node current = head;
        while (current != null) {
            System.out.print(current.getData() + " ");
            current = current.getNext();
        }
        System.out.println();
    }

    public static void main(String[] args) {
        LinkedList linkedList = new LinkedList();
        linkedList.add(1);
        linkedList.add(2);
        linkedList.add(3);
        linkedList.print();
    }
}

該示例中,Node類表示鏈表中的節(jié)點,包含一個整數(shù)數(shù)據(jù)和一個指向下一個節(jié)點的指針。LinkedList類表示鏈表,包含一個指向頭節(jié)點的指針和一些基本操作方法,如添加節(jié)點和打印鏈表。在main方法中,創(chuàng)建一個LinkedList對象,并添加一些節(jié)點,然后打印鏈表中的數(shù)據(jù)。輸出結(jié)果為:1 2 3。

0