温馨提示×

java怎么遍历单链表

小亿
97
2023-11-16 09:10:11
栏目: 编程语言

在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()方法遍历并打印链表中的每个元素。

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

0