温馨提示×

java单向链表实现代码怎么写

小亿
82
2023-12-15 02:46:40
栏目: 编程语言

下面是一个简单的Java单向链表的实现代码:

class Node {
    int data;
    Node next;

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

class LinkedList {
    Node head;

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

    // 在链表末尾添加一个节点
    public void addNode(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 printList() {
        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.addNode(1);
        list.addNode(2);
        list.addNode(3);
        list.addNode(4);

        // 打印链表
        list.printList();
    }
}

在上面的代码中,Node类表示链表的节点,其中包含一个data变量表示节点的数据,以及一个next变量表示指向下一个节点的引用。

LinkedList类表示链表,其中包含一个head变量表示链表的头节点。addNode方法用于在链表末尾添加一个新节点,printList方法用于打印链表的所有元素。

Main类的main方法中,创建一个LinkedList对象,然后调用addNode方法添加节点,并最后调用printList方法打印链表的元素。输出结果为:1 2 3 4。

0