Reputation: 101
I am trying to implement the add method for the linkedlist , it should take any data type, but I am kind of lost and is not working, any help will be appreciated.
public class LinkedList <T>extends AbstractList {
private class Node {
T data;
Node next;
Node(T data, Node next) {
this.data = data;
this.next = next;
}
Node(T data) {
this(data, null);
}
}
Node first;
Node last;
public LinkedList() {
first = null;
last = null;
}
@Override
public boolean add(T item) {
Node newNode = new Node((T)item);
if (isEmpty()) {
first = newNode;
last = first;
return true;
}
last.next = newNode;
last = null;
return true;
}
}
Upvotes: 1
Views: 2656
Reputation: 65811
You need:
last.next = newNode;
last = newNode;
Be careful that you understand why.
Before you add the new node, last
is a reference to the last entry in the list.
What you want to do is to point its next
reference to this new node.
The second line then updates last
to refer to this new one too.
Upvotes: 0
Reputation: 116266
You don't tell us your concrete problem, so we can't fix it, only guess.
One issue I see though is that you extend AbstractList
as a raw (nongeneric) type - your declaration should be instead
public class LinkedList<T> extends AbstractList<T> { ... }
Upvotes: 1