1

我的Node类,代表链表的一个节点,定义如下:

public class Node
{
    Node next;
    String data;

    public Node (String data)
    {
        this.data = data;
    }
}

我正在这样使用它:

Node node, head, tail;
String name; // name to be entered
int count = 0;

// initialize the head to null

head = null;

do
{
    System.out.print ("Enter a name. Type q to end.");
    name = stdin.readLine ();

    // create a new node if the user doesn't type q
    if (!name.equals ("q"))
    {
        node = new Node (name);
        node.next = head;
        count++;

        // update the head to point to the new front of the list
        head = node;
    }
}
while (!name.equals ("q"));  // loop continues until "quit" selected
node = head; 

假设我想将名称备份到一个方法中,以防我修改原始列表。我怎样才能做到这一点?无需将其写入文件。

Name 是存储在链接列表中的变量,在用户按下 q 后,我想修改列表,同时保留用户存储的内容作为备份,以防他/她想要回溯或查看原始列表。

4

2 回答 2

1

It would be better to make the Node immutable. So every time when you want to modify the node, you create a new node. And store the old one in the linklist history.

于 2012-12-04T15:39:49.730 回答
0

所以听起来好像您想为链表中的每个元素保留先前名称的历史记录。我建议您在链表的每个节点中存储一个数组或链表,以显示该项目的先前历史。例如:

public class Node
    {
    Node next;
    String data;
    LinkedList<String> history;

    public Node (String data)
    {
        this.data = data;
    }
}

您可以通过多种方式填充它,这完全取决于您的用例。

另外,为什么要实现自己的链表?Java 已经带有一个链表实现(java.util.LinkedList)。如果您需要链表种类的有序列表,我建议您使用它。如果你这样做了,那么创建一个包含在其中的新数据结构,其中包含名称和历史记录,然后只需维护其中的历史记录,例如:

public class DataItem
    {
    String data;
    LinkedList<String> history = new LinkedList<>();

    public DataItem (String data)
    {
        this.data = data;
    }

    public void setData (String data)
    {
        this.history.add(0, this.data);
        this.data = data;
    }
}

最后,请记住字符串在 Java 中是不可变的。因此,不能修改字符串。您只需要在某处保留对先前字符串的引用,您不需要复制该值。

要最终复制对象树,您需要执行所谓的深度复制,基本上是遍历完整结构和所有集合,并将每个对象克隆为一个新对象。

于 2012-12-04T15:33:36.693 回答