Recursive

Count the number of elements in a singly linked list

Pinterest LinkedIn Tumblr

Write a program to count the number of elements in the linked list.

source Code

package com.dsacode.Algorithm.recursive;
 
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
public class CountNumberOfElements {
 
    public static void main(String[] args) {
         List < Integer > myNumbers= Arrays.asList(12, 12, 14, 16, 16);
         System.out.println("List of Array items: "+myNumbers.toString());
            Map < Integer, Integer > countMap = new HashMap < Integer, Integer >();
            for(int i=0; i < myNumbers.size(); i++){
                Integer myNum = myNumbers.get(i);
                if(countMap.get(myNum)!= null){
                     Integer currentCount = countMap.get(myNum);
                     currentCount = currentCount.intValue()+1;
                     countMap.put(myNum,currentCount);
                }else{
                    countMap.put(myNum,1);
                }
            }
 
           Set < Integer > keys = countMap.keySet();
           for(Integer num: keys){
               System.out.println("Number "+num.intValue()+" count "+countMap.get(num).intValue());
           }
 
    }
 
}

Output

List of Array items: [12, 12, 14, 16, 16]
Number 16 count 2
Number 12 count 2
Number 14 count 1

Algorithm Explanation

Store the list of elements to an array list.
Use map to find the number of elements in the list.
If the element already in the map, get the value and increment by 1.
If the element not in the map, create the value and add to 1.

Time Complexity

Best CaseAverage CaseWorst Case
O(1)

Reference

https://www.mathworks.com/help/matlab/ref/numel.html

Write A Comment