can you please explain how the algorithem with the following code works ,and how
ID: 3540159 • Letter: C
Question
can you please explain how the algorithem with the following code works ,and how the method supposed to work please explain in your own words
import javax.swing.JOptionPane;
public class PLinkedList {
private PersonNode head;
public PLinkedList() {
head = null;
}
public void append(Person x) {
PersonNode n = new PersonNode(x);
PersonNode current = head;
if (head == null)
head = n;
while (current.getNext() != null) {
current = current.getNext();
}// while
current.setNext(n);
}
public void insert(Person x) {
PersonNode n = new PersonNode(x);
PersonNode current = head;
boolean flag = false;
if (head == null)
head = n;
else {
if (n.getData().getAge() < current.getData().getAge()) {
// case 1 new node becomes head
n.setNext(head);
head.setPrevious(n);
head = n;
} else {
while (current.getNext() != null && !flag) {
if (n.getData().getAge() <= current.getNext().getData().getAge()) {
flag = true;
}// case 2 insert node in the middle
else {
current = current.getNext();
}// if else(n<current.getNext())
}// while
// case 3 new Node gets appended. Another way to create boolean
// expression
n.setNext(current.getNext());
if(current.getNext()!=null)
current.getNext().setPrevious(n);
n.setPrevious(current);
current.setNext(n);
}
}
}
int[] countAges()
{
int[] ages = new int[100];
for(int i = 0;i<100;i++)
{
ages[i] = 0;
}
//travel from head to the end of list
PersonNode current = head;
//until get to end of list
while (current != null) {
//count the age
ages[current.getData().getAge()]++;
//move to next person
current = current.getNext();
}
return ages;
}
public static void main(String args[]) {
//add number of person
PLinkedList list = new PLinkedList();
list.insert(new Person("1", 22));
list.insert(new Person("2", 23));
list.insert(new Person("3", 22));
list.insert(new Person("4", 4));
list.insert(new Person("5", 4));
list.insert(new Person("6", 4));
list.insert(new Person("7", 5));
list.insert(new Person("8", 20));
list.insert(new Person("9", 22));
//call countAges function
int[] agesCount = list.countAges();
int max = 0;
int maxAge = 0;
for(int i = 0;i<100;i++)
{
if(max<agesCount[i])
{
max = agesCount[i];
maxAge = i;
}
}
System.out.println("The most age is "+maxAge);
}
}
Explanation / Answer
Code is incomplete. Person and PersonNode classes are missing
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.