java怎么遍历单链表

41次阅读
没有评论

共计 560 个字符,预计需要花费 2 分钟才能阅读完成。

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

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

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-12发表,共计560字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)