表題のコードを見つけて何をやってるのか延々悩む日々を送ってましたが、下記youtubeビデオが非常にわかりやすかったのでメモ
Nodeが何個あるか見つける簡単なコード
はい、youtube上ででてきた問題ですw
class Node { int data; Node next; public Node(int data) { this.data = data; } } public class NodeTest { public static void main(String[] args) { Node head = new Node(2); Node nodeB = new Node(4); Node nodeC = new Node(6); Node nodeD = new Node(8); head.next = nodeB; nodeB.next = nodeC; nodeC.next = nodeD; System.out.println(countNodes(head)); } public static int countNodes(Node head) { int cnt = 1; while(head.next != null) { head = head.next; cnt++; } return cnt; } }