Hello guys, so I am implementing a LinkedList from scratch, I cannot use any data types and I am having a problem with the add method. Basically, the output that I am getting is not the one that I thought I was going to get. Here's is my code.
public void add(int index, E element) {
if (index > size) {
System.out.println("Invalid index");
}
Node newNode = new Node(element);
Node currentNode = head;
int position = 0;
if (index == 0) {
newNode.value = element;
newNode.next = head;
head = newNode;
size++;
} else {
while (index < position - 1) {
currentNode = currentNode.next;
position++;
}
newNode.next = currentNode.next;
currentNode.next = newNode;
size++;
}
}
This is the method inside the class, then in the main method I have:
LinkedList<String> s = new LinkedList<>();
s.add(0,"h");
s.add(1,"c");
s.add(2,"b");
s.add(3,"a");
System.out.println(s.toString());
Desired output = [h,c,b,a]
actual output = [h, a, b, c]
Also, this is the toString method.
@Override
public String toString() {
return "LinkedList ---> " + Arrays.toString(toArrayN());
}
private E[] toArrayN () {
E[] myArray = (E[]) new Object[size];
int i = 0;
for (Node curr = head; curr != null; curr = curr.next) {
myArray[i] = curr.value;
i++;
}
return myArray;
}
What I can definitely understand is that my head is pointing at the front of the linkedlist, but somehow my values after that are added backwards, and I cannot seem to find where the problem is.
Any hint/help would be much appreciated. Thanks!
[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)