gpt4 book ai didi

java - 链表的 add() 方法

转载 作者:行者123 更新时间:2023-12-01 07:21:21 24 4
gpt4 key购买 nike

我正在尝试创建一种将节点添加到链接列表的方法,但到目前为止尚未成功。这是我的代码和我的成员变量:

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

关于java - 链表的 add() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36272834/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com