For this lab, I cannot for the life of me figure out what to do here. This is part of the prompt for my assignment:
//return the data at specific position if it is present
E getData(int index)
I assume that I am to display a value tied to a node using indexes. However, my professor has us doing this in an odd way so my linked list exists, but I don't know how to call to it.
The code below is what makes the list appear in the console:
public static void main(String[] args) {
LinkedList<Integer> myList = new LinkedList<Integer>();
//Add Data
myList.addData(4);
myList.addData(2);
myList.addData(1);
myList.printList();
//Add Data At End
myList.addDataAtEnd(5);
System.out.println();
myList.printList();
//Add Data At Specific Spot
myList.addDataSpecificSpot(3);
System.out.println();
myList.printList();
the methods are below:
printList
public void printList() {
Node<E> current = head;
while(current != null) {
System.out.print(current.data + " --> ");
current = current.next;
}
}
addData
public void addData(E data) {
Node<E> newNode = new Node<E>(data);
newNode.next = head;
head = newNode;
}
addDataAtEnd
public void addDataAtEnd(E data) {
Node<E> newNode = new Node<E>(data);
Node<E> current = head;
while(current.next != null) {
current = current.next;
}
newNode.next = null;
current.next = newNode;
}
addDataSpecificSpot
public void addDataSpecificSpot(E data) {
Node<E> newNode = new Node<E>(data);
Node<E> current = head;
while(current.next.next.next != null) {
current = current.next;
}
newNode.next = current.next;
current.next = newNode;
}
So, after all that happens, the console outputs this:
1 --> 2 --> 4
1 --> 2 --> 4 --> 5
1 --> 2 --> 3 --> 4 --> 5
How would I implement the getData method to find a value within a certain index? I just am at a loss for what to do.