add()方法用于链表

Lar*_*ere 0 java methods linked-list add nodes

我正在尝试创建一个方法,将一个节点添加到链表,但到目前为止一直没有成功.这是我的代码与我的成员vars:

private Object data; 
private int size = 0;
private Node head = null; 
private Node tail = null;

    public void add(Object item){
    Node temp = head;
    if (head != null) {
        // THIS IS THE PROBLEM SITE

        while(temp.getNext()!=null){
            temp=temp.getNext();
        }
        //set next value equal to item
        Node ab = (Node) item; // It says this is an invalid cast. How do I get around this??
        ab.setNext(ab);

    } 
    else{
        head = new Node(item);
    }
    size++;
}
Run Code Online (Sandbox Code Playgroud)

这里也是我的Node类供参考:

public class Node {

// Member variables.
private Object data; // May be any type you'd like.
private Node next;

public Node(Object obj) {
    this.data = obj; // Record my data!
    this.next = null; // Set next neighbour to be null.
}
// Sets the next neighbouring node equal to nextNode
public void setNext(Node nextNode){
    this.next=nextNode;
}
// Sets the item equal to the parameter specified.
public void setItem(Object newItem){
    this.data = newItem;
}
// Returns a reference to the next node.
public Node getNext(){
    return this.next;
}
// Returns this node ís item.
public Object getItem() {
    return this.data;   
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的时间!

max*_*ede 7

您不希望将您item的节点转换为节点,您希望创建一个新节点并将其设置dataitem

替换这个:

Node ab = (Node) item; // It says this is an invalid cast. How do I get around this??
ab.setNext(ab);
Run Code Online (Sandbox Code Playgroud)

通过这样的事情:

Node newNode  = new Node();
newNode.setData(item);
temp.setNext(newNode);
Run Code Online (Sandbox Code Playgroud)