Java Write a complete display() method for the LList class. LList implements Lis
ID: 3599516 • Letter: J
Question
Java
Write a complete display() method for the LList class.
LList implements ListInterface using linked nodes.
The method prints to the console the list index of each element along with the element.
Be sure to account for all possible times when the method could be invoked.
For full credit, write a method that is efficient (meaning better than O(n2)).
The method header is:
public void display()
For this question, you are writing code at the implementation level. This means you have access to the private instance data variables:
private Node firstNode
private int numberOfEntries
You can assume the following methods are already implemented:
Note that toArray is not listed and should not be used in your solution.
public void add(T newEntry)
public void add(int newPosition, T newEntry)
public boolean isEmpty()
public boolean contains(T anObject)
public T remove(int givenPosition)
public T replace(int givenPosition, T newEntry)
public T getEntry(int givenPosition)
public int getLength()
public void clear()
Explanation / Answer
Hi friend, you can display all content of the list like that:
This takes O(n^2) time
public void display() {
for(int i=0; i<getLength(); i++) {
System.out.println(getEntry(i));
}
}
Efficient Method:
public void display1() {
Node currNode = firstNode;
while(currNode != null) {
System.out.println(currNode.getElement());
currNode = currNode.getNext();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.