【问题标题】:Adding an object to the end of the circular list将对象添加到循环列表的末尾
【发布时间】:2015-03-18 03:14:41
【问题描述】:

我在这里有一个工作代码,它在末尾添加了一个新节点。但由于某种原因,添加第三个节点后,第一个节点消失了。

这是方法

public boolean add(Token obj)  {

    if(obj == null){
        return false;
    }

    if (head == null){
        head = new Node(null, null, obj);
        return true;
    }

    while (head.next != null){
        head = head.next;
    }
    head.next = new Node(null,null,obj); // Next, Previous , Object

    return true;

}

用这个创建一个新节点

当我像这样从 main 调用它时

public static void main(String[] args) {

    CircularList test = new CircularList();

    Token something = new Token("+");
    test.add(something);
    test.add(new Token(2));
    test.add(new Token(5));



    System.out.println(test.toString());


}

}

我的输出是

"列表包含 2 , 5"

所以如果我删除第三个添加新令牌,即 Token(5),第一个又会恢复。

对此有任何帮助吗?提前致谢

【问题讨论】:

    标签: java nodes circular-list


    【解决方案1】:
    while (head.next != null){
        head = head.next;
    }
    

    错了。U换头指针..

    Node temp=head;
    while(temp.next!=null)
        temp=temp.next
    temp.next=new Node(null,null,obj);
    

    【讨论】:

      猜你喜欢
      • 2011-06-16
      • 1970-01-01
      • 1970-01-01
      • 2021-06-05
      • 2015-07-17
      • 1970-01-01
      • 2011-02-09
      • 2023-03-07
      • 2015-08-29
      相关资源
      最近更新 更多