温馨提示×

java怎么实现链表结构

小亿
82
2023-12-15 02:34:13
栏目: 编程语言

在Java中,可以通过自定义类实现链表结构。以下是一个简单的链表实现示例:

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类表示链表中的节点,包含一个整数数据和一个指向下一个节点的指针。LinkedList类表示链表,包含一个指向头节点的指针和一些基本操作方法,如添加节点和打印链表。在main方法中,创建一个LinkedList对象,并添加一些节点,然后打印链表中的数据。输出结果为:1 2 3。

0