In: Computer Science
goal Find the average of the elements in the list (list could
have any number of elements).
If the average is a decimal number, return only the integer part.
Example: if average=10.8, return 10
Example: if list={10, 20, 30, 40, 50}, the method should return:
30
import java.io.*;
import java.util.Scanner;
class Node {
int data;
Node next;
Node(int d){ // Constructor
data = d;
next = null;
}
}
class LinkedList {// a Singly Linked List
Node head; // head of list
public void insert(int data){ // Method to insert a
new node
Node new_node = new Node(data); //
Create a new node with given data
new_node.next = null;
if (head == null) // If the Linked
List is empty, then make the new node as head
head =
new_node;
else {// Else traverse till the
last node and insert the new_node there
Node last =
head;
while (last.next
!= null)
last = last.next;
last.next =
new_node; // Insert the new_node at last node
}
}
}
class Main {
public static void main(String[] args)
{
LinkedList list = new
LinkedList();/* Start with the empty list. */
Scanner scan = new
Scanner(System.in);
int num;
for (int i=0; i<10; i++){//Read
list values
num =
scan.nextInt();
list.insert(num);
}
System.out.println(""+getAvg(list));
}
public static int getAvg(LinkedList list) {
//goal Find the average of the
elements in the list (list could have any number of
elements).
//If the average is a decimal
number, return only the integer part. Example: if average=10.8,
return 10
//Example: if list={10, 20, 30, 40,
50}, the method should return: 30
}
}
import java.io.*;
import java.util.Scanner;
class Node {
int data;
Node next;
Node(int d){ // Constructor
data = d;
next = null;
}
}
class LinkedList {// a Singly Linked List
Node head; // head of list
public void insert(int data){ // Method to insert a new node
Node new_node = new Node(data); // Create a new node with given data
new_node.next = null;
if (head == null) // If the Linked List is empty, then make the new node as head
head = new_node;
else {// Else traverse till the last node and insert the new_node there
Node last = head;
while (last.next != null)
last = last.next;
last.next = new_node; // Insert the new_node at last node
}
}
}
public class Main {
public static void main(String[] args)
{
LinkedList list = new LinkedList();/* Start with the empty list. */
Scanner scan = new Scanner(System.in);
int num;
for (int i=0; i<5; i++){//Read list values
num = scan.nextInt();
list.insert(num);
}
System.out.println(""+getAvg(list));
}
public static int getAvg(LinkedList list) {
// declare variables
int num = 0;
int sum = 0;
// if head is null means list is empty
if (list.head == null) {
return -1;
}
// get the current
Node current = list.head;
// loop till end
while (current != null) {
num += 1; // count the length
sum += current.data; // calculate sum
current = current.next; // make list point to next
}
// return the average
return sum/num;
}
}

FOR HELP PLEASE COMMENT.
THANK YOU
FOR HELP PLEASE COMMENT.
THANK YOU,