JAVA - Given a linked list of integers, write a method that computes and prints
ID: 3726474 • Letter: J
Question
JAVA
- Given a linked list of integers, write a method that computes and prints the prefix sums which is illustrated below with an example
- If the array list has values 5,3,2,9,3,15,22 from head to tail, the prefix sums would be 5, 8, 10, 19, 22, 37,59 which is the sum of the first k values where k=0, 1,2,.. size()-1. You will output the prefix sums exactly as above on a single line, comma separated. Make sure your code works for a linked list of any size, not just for the example above.
- Same as above, except you compute the prefix sums of the reverse of the list. For the example above, you should get 22,37, 40, 49,51,54, and 59.
Explanation / Answer
import java.util.*;
public class Test{
public static void main(String args[]){
int sum=0,n=0;
Scanner sc= new Scanner(System.in);
System.out.println("Enter the number of elements needed");
n=sc.nextInt();
LinkedList<Integer> list=new LinkedList<Integer>();
for(int i=0;i<n;i++)
{
int x=0;
System.out.println("Enter the element to be inserted in list");
x=sc.nextInt();
list.add(x);
}
Iterator<Integer> itr=list.iterator();
while(itr.hasNext()){
sum+=(int)itr.next();
System.out.println(sum);
}
Collections.reverse(list);
Iterator<Integer> it=list.iterator();
while(it.hasNext()){
sum+=(int)it.next();
System.out.println(sum);
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.