void append (Node n) { //here construct the my list }
void remove(Node n) { find and remove n from the list and change the pointers as well }
void myMethod (LinkedList list, Node n) {
list.remove(n);
}
static main () {
List
for (int i=0; i< 10; i++) ll.append(new Node (i));
myMethod (ll, new Node (4));
//here I'd like that linkedList wasn't changed !!!! (but it's changed)
}
Can I do value passage in this case? thanks
AlanPosted Nov 1, 2007, 4:46 PM
I've had a go at coding a Clone() method to add to your LinkedList class:
public LinkedList Clone()
{
LinkedList ll = new LinkedList(); //creates a new 'start' node
Node n = start;
Node copy = null;
while( (n = n.Next) != null)
{
copy = new Node(n.Value);
ll.addNode(copy);
}
return ll;
}
Incidentally, I assume you're doing this as a project because there's already a LinkedList class in the framework, though it's doubly rather than singly linked:
http://msdn2.microsoft.com/en-us/library/he2s3bh7(vs.80).aspx
AlanPosted Nov 1, 2007, 2:11 PM
If you want to preserve the original LinkedList, then there's no alternative to copying it first.
The Nodes themselves will also need to be cloned and the pointers fixed up to point to the copies.
MarcoPosted Nov 1, 2007, 1:44 PM
AlanPosted Nov 1, 2007, 12:50 PM
There seems to be a some confusion in your code whether you're creating a List or a LinkedList object but I'm assuming that 'll' is in fact a LinkedList variable.
Just as a general point, whenever you pass a reference type object to a method 'by value', there is nothing you can do in C# to prevent the method from changing the state of the object. There are no 'const' parameters like there are in C++ and even those can be cast away.
However, I suspect your problem is that you're trying to delete a newly created Node object from the LinkedList with this method call:
myMethod (ll, new Node (4));
You should only be deleting Node objects which already exist. So, unless you have an external reference to the Node to be removed which you can pass to the method, a better idea would be to pass the value of the Node to the method, search for that, remove the corresponding Node and fix up the pointers.