简体   繁体   中英

add() method for a linked list

I'm trying to create a method that will add a node to a linked list but so far have been unsuccessful. Here's my code with my member 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++;
}

Also here's my Node class for reference:

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

Thanks for your time!

you don't want to cast your item as a node, you want to create a new node and set the data in it to be the item

replace this :

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

by something like this :

Node newNode  = new Node();
newNode.setData(item);
temp.setNext(newNode);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM