public class arrlistlen {
public static void main(String[] args) {
arrlistlen test = new arrlistlen ();
//A = linked list
//A[0] = head
//A[K] = value of node at index K
//A[K] = -1 = last node of list
//A[K] != -1 = get the next index from this value
// return number of connections
int[] A = {1, 4, -1, 3, 2};
System.out.println(test.solution(A));
int[] B = {-1};
System.out.println(test.solution(B));
}
public int solution(int[] A){
int index = 0;
int head = A[index];
int count = 0;
while (head != -1){
count++;
index = head;
head = A[index];
}
return ++count; //adds -1
}
}
No comments:
Post a Comment