Java 链接列表的add()方法
我正在尝试创建一个方法,将一个节点添加到一个链接列表中,但到目前为止还没有成功。以下是我的成员变量代码:Java 链接列表的add()方法,java,methods,linked-list,add,nodes,Java,Methods,Linked List,Add,Nodes,我正在尝试创建一个方法,将一个节点添加到一个链接列表中,但到目前为止还没有成功。以下是我的成员变量代码: 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
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++;
}
这里还有我的节点类供参考:
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;
}
谢谢你的时间 您不希望将项目强制转换为节点,而是希望创建一个新节点并将其中的数据设置为项目 替换此项:
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);
你能解释一下“不成功”是什么意思吗。您是否遇到错误?我相信这是的重复。将来,您应该添加您遇到的异常,以便更容易为其他人隔离/理解问题。