どのように 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()メソッドを使ってリスト内の各要素を順次たどり、出力しています。

実際の利用においては、連結リストに挿入や削除、検索などの操作を追加する必要があるかもしれません。

bannerAds