My Node class, representing a node of a linked list, is defined like this:
public class Node
{
Node next;
String data;
public Node (String data)
{
this.data = data;
}
}
and I’m using it like this:
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;
Suppose I wanted to back the names up to a method in case I modify the original list. How can I do this? Without writing it to a file.
Name is the variable that gets stored in the linked list and after the user presses q I want to modify the list while keeping what the user stored as a back up in case he/she wants to backtrack or see the original list.
So it sounds as though you want to keep a history of the prior names for each element in the linked list. I would suggest that you store an array or linked list within each node of the linked list that shows the prior history of that item. For instance:
You could populate this in many ways, that all really depend upon your use case.
Also, why implement your own linked list? Java already comes with a linked list implementation (java.util.LinkedList). I’d suggest using this if you need an ordered list of the linked list variety. If you did this, then create a new data structure to be contained within it that has a name and history, then just maintain the history within that, such as:
Ultimately, remember that strings are immutable in Java. So, a string cannot be modified. You only need to keep a reference to the prior string somewhere, you don’t need to copy the value.
To ultimately copy a tree of objects, you need to do what’s called a deep copy, basically going through the full structure and all collections, and cloning each object into a new object.