Write a program using Java to find the number of common elements of two linked lists.
e.g. 1 3 5 7 null
2 3 7 9 11 null
Output: 2
import java.util.Arrays;
import java.util.LinkedList;
public class solution {
public static void main(String[] args) {
LinkedList<Integer> l1 = new LinkedList<Integer>(Arrays.asList(1, 3, 5, 7, null));
LinkedList<Integer> l2 = new LinkedList<Integer>(Arrays.asList(2, 3, 7, 9, 11, null));
int counter = 0;
for (int i = 0; i < l1.size() - 1; i++) {
if (l2.contains(l1.get(i))) {
counter ++;
}
}
System.out.println(counter);
}
}
Comments
Leave a comment