java怎么遍历单链表

700
2023/12/13 9:10:11
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Java中,遍历单链表可以使用循环或递归的方式。以下是使用循环遍历单链表的示例代码:

class Node {
    int data;
    Node next;

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

class LinkedList {
    Node head;

    public void traverse() {
        Node current = head;

        while (current != null) {
            System.out.print(current.data + " ");
            current = current.next;
        }
    }
}

public class Main {
    public static void main(String[] args) {
        LinkedList list = new LinkedList();

        list.head = new Node(1);
        Node second = new Node(2);
        Node third = new Node(3);

        list.head.next = second;
        second.next = third;

        list.traverse();
    }
}

以上代码创建了一个简单的单链表,并使用traverse()方法遍历并打印链表中的每个元素。

注意:在实际应用中,可能需要在链表中添加其他操作,如插入、删除、查找等。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: java为什么无法加载指定的文件