1

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;
}

}

4
  • 2
    Is something not working? What is the problem? Commented Apr 17, 2012 at 15:55
  • last = null; looks to be incorrect. last = newNode; maybe? Also you should genericise Node Commented Apr 17, 2012 at 15:57
  • last = newNode and last.next = null Commented Apr 17, 2012 at 16:02
  • +1 to the above comments, also consider peeking into java.util.LinkedList implementation for hints. Commented Apr 17, 2012 at 16:07

2 Answers 2

1

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>  { ... }
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.