Return toString 方法中动态堆栈链表的所有值

Return all values of a dynamic stack linkedlist in a toString method

我试图找出如何使用 toString 方法输出“最新”节点的所有版本,但我对如何使 while 循环在这种情况下正常工作感到困惑。我想知道是否有一种方法可以做到这一点。

这是 toString() 方法:

    public String toString() {

        String output = "key: " + key ;
        Node<VersionedObject> currNode = latest;
        
        while (latest != null){
            output += latest+ "\n\t";
            latest.setNext(latest);
        } // This isn't particularly working


        //return "key: " + key +"\n\t" +latest + "\n\t" + latest.getNext(); // placeholder but it's getting closer. This one is INSANELY specific

        return output;
    }

,创建列表的方法如下:

    public StackOfVersionedObjects(String key, final Object object) {
        this.key = key;
        VersionedObject vrObject = new VersionedObject(object);
        latest = new Node<VersionedObject>(vrObject);
    }

,这是我的节点 class:

    public class Node<T> {

    private T    data;
    private Node next;

    public Node() {
        data = null;
        next = null;
    }

    public Node(T data) {
        this.data = data;
        next      = null;
    }

    public T getData() {
        return data;
    }

    public Node<T> getNext() {
        return next;
    }

    public void setData(T data) {
        this.data = data;
    }

    public void setNext(Node<T> next) {
        this.next = next;
    }

    @Override
    public String toString() {
        return data.toString();
    }
}

latest 更改为 currentNode 并像这样循环

@Override
public String toString() {
    StringBuilder builder = new StringBuilder();
    builder.append("key: " + key);
    Node<VersionedObject> currNode = latest;
  
    while (currNode != null){
        builder.append(currNode + "\n\t");
        currNode = currNode.getNext();
    }

    return builder.toString();
}