Write a program to count the number of times a given integer appears in a LL.
import java.util.LinkedList;
import java.util.Scanner;
public class Test {
public static Integer findNumberOfElementInLinkedList(LinkedList linkedList, int element) {
int numberOfOccurrences = 0;
if (linkedList == null || linkedList.isEmpty()) {
System.out.println("List is empty");
}
else {
if (linkedList.contains(element)){
for (int i = 0; i < linkedList.size(); i++){
if (element == (int) linkedList.get(i)){
numberOfOccurrences++;
}
}
}
}
return numberOfOccurrences;
}
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
LinkedList<Integer> list = new LinkedList<>();
System.out.println("Enter number of elements in list: ");
int numberOfElements = scan.nextInt();
int numberForSearch;
System.out.print("Enter elements: ");
for (int i = 1; i <= numberOfElements; i++){
list.add(scan.nextInt());
}
System.out.println("Enter the number for which you want to count the number of occurrences in the list: ");
Scanner scanner = new Scanner(System.in);
numberForSearch = scanner.nextInt();
System.out.println(list);
System.out.println("The number of times this item appears in the list - " + findNumberOfElementInLinkedList(list, numberForSearch));
}
}
Comments
Leave a comment