Hi how can I get the average of the linked list? I mean take the whole list and divide by two...
eg: average = 13213216546847651321 / 2
any help I'm confuse on how to start...
Printable View
Hi how can I get the average of the linked list? I mean take the whole list and divide by two...
eg: average = 13213216546847651321 / 2
any help I'm confuse on how to start...
You counld start on how to input the number into your program.
Try googling the Scanner function.
That one might help. :)
You calculate the average the same way as if you had a bunch of numbers written on paper. Add hte numbers and divide the sum by how many numbers there are. If all the values are store in a List or some other Collection then check out what methods the Collection has to allow you to access the numbers. And of course you will need a loop and a variable to hold the sum.
If you are asking how to get the average of the elements of a linked list, the answer is to add every element to a total and divide by the number of elements.
Dividing by 2 only gives the average when there are 2 elements.
Unless you have a special list (1,2,3,4,5,6,7,8,9,) for example, where the center element is the average, in which case the number of elements / 2 gives the index of the element at the center of the list, and supposedly contains the average.
If you still have a question, try to give details on what you are trying to do and reword the question to be clear about what part you are having problems with.
actually my program is getting the sum of two (2) big numbers using linked list and not using BigInteger or BigDecimal dataTypes and I figure it out how to that.. My problem now is getting the average of the sum that is why I'am dividing that sum into two (2) only to get the average...
so far I got this but it returns null so sad.. tsk3
Code :Node getAverage(Node res) { Node pointer = res; int carry = 0; while (pointer != null) { if (carry == 0) { carry = pointer.data % 2; pointer.data = pointer.data / 2; } else { carry = (pointer.data + 10) % 2; pointer.data = (pointer.data + 10) / 10; } pointer = pointer.next; } return pointer; }
Lets drop the code back to pseudo-code and analyze the algorithm.
while ( pointer is NOT null )
// do some things
// else do some things
// ok that is enough doing
Now that pointer is null, exit the loop.
return pointer
Why does the method return null? Because you told it to exit the loop when pointer is null and then return pointer.
Have two variables
- long counter
- long sum
use them wisely while iterating through the LL.
at the end print avg=sum/counter