Linux 拨号vps windows公众号手机端

java怎么遍历单链表

lewis 8年前 (2017-09-09) 阅读数 12 #程序编程
文章标签 Java

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

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

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门