Don't understand why my addFirst() method doesn't work. When I ask for the size of list, it returns 1 but I added 3 words. It looks like the program takes only one element and forgets about the previous. I removed all the other irrelevant code and left only the one connected to my question with the addFirst() method. Here's the code:
Node object:
public class Node<Type> {
private Type data;
private Node<Type> next;
public Node(Type data) {
this.data = data;
next = null;
}
public Type getData() {
return data;
}
public void setData(Type data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
Main Method:
public class MyMain<Type> {
public static void main(String[] args) {
MyList<String> list = new MyList<String>();
System.out.println("The size is: " + list.size());
String s1 = "Summer";
String s2 = "Spring";
String s3 = "Winter";
list.addFirst(s2);
list.addFirst(s3);
list.addFirst(s1);
System.out.println("The size is: " + list.size());
}
}
Linked List:
public class MyList<Type> {
private Node<Type> head;
public MyList() {
head = null;
}
public int size() {
int length = 0;
Node<Type> current = head;
while (current != null) {
current = current.getNext();
length++;
}
return length;
}
public void addFirst(Type data) {
Node<Type> newFirst = new Node<Type>(data);
if (head == null) {
head = newFirst;
} else {
newFirst = newFirst.getNext();
newFirst = head;
head = newFirst.getNext();
}
}
}
Very confused and would appreciate any help, thank you!