Reputation: 3
I am trying to figure what's wrong with this LinkedList implementation. The result is not what I expected, I thought it should be: 9 4 2 7 5. However, when I run it, only 5 was added. Could someone please explain why? Thanks a lot!
public class LinkedList {
LinkedList next;
int value;
public LinkedList(int value) {
this.value = value;
next = null;
}
public void add(int n, LinkedList k) {
LinkedList node = new LinkedList(n);
node.next = k;
k = node;
}
}
public class LinkedListDemo {
public static void main(String[] args) {
LinkedList l = new LinkedList(5);
l.add(7,l);
l.add(2,l);
l.add(4,l);
l.add(9,l);
while(l != null) {
System.out.println(l.value);
l = l.next;
}
}
}
Upvotes: 0
Views: 107
Reputation: 109547
Adding in front would need to change the first node, one solution:
public LinkedList add(int n){
LinkedList node = new LinkedList(n);
node.next = this;
return node;
}
l = l.add(7);
Upvotes: 0