【问题标题】:add() method for a linked list链表的 add() 方法
【发布时间】:2016-03-28 23:20:08
【问题描述】:

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

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

感谢您的宝贵时间!

【问题讨论】:

  • 你能解释一下“不成功”是什么意思吗?你有错误吗?
  • 我相信这是stackoverflow.com/questions/5797548/…的副本
  • 将来,您应该添加您得到的异常,以便其他人更容易隔离/理解问题。

标签: java methods linked-list add nodes


【解决方案1】:

您不想将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);

【讨论】:

    猜你喜欢
    • 2023-03-12
    • 2021-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多