我的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后,我想要修改列表,同时保留用户存储的内容作为备份,以防他/她想要回溯或查看原始列表。
发布于 2012-12-04 23:33:37
因此,听起来您似乎想要保留链表中每个元素的先前名称的历史记录。我建议您在链表的每个节点中存储一个数组或链表,以显示该项的先前历史记录。例如:
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-04 23:39:50
最好将Node设置为不可变的。因此,每次要修改节点时,都会创建一个新节点。并将旧的存储在链表历史中。
https://stackoverflow.com/questions/13706194
复制相似问题