簡體   English   中英

鏈表的add()方法

[英]add() method for a linked list

我正在嘗試創建一種將節點添加到鏈表中的方法,但到目前為止仍未成功。 這是我的成員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++;
}

這也是我的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;   
}

謝謝你的時間!

您不想將item投射為節點,而是要創建一個新節點並將其中的data設置為item

替換為:

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

通過這樣的事情:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM