create a linkedlist and add 5 integer elements to that.calculate and print the sum of odd elements of the list
1 2 3 4 5
class Main {
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>();
for(int i = 1; i<=5; i++){
list.add(i);//1 2 3 4 5
}
int sum = 0;
for (int num : list)//num=1 {
if (num % 2 != 0)
sum += num;
}
System.out.println(“Sum of odd elements: ” + sum);
}
}
—————————
public int sumofodd()
{
int sum=0;
Node temp=head;
while(temp!=null)
{
if(temp.data % 2 != 0)
{
sum+=temp.data
}
temp=temp.next
}
}