Reputation: 5
I'm learning C# and I've made a recursive insert-method for a linked list:
public static int recursiveInsert(ref int value, ref MyLinkedList list) {
if (list == null)
return new MyLinkedList(value, null);
else {
list.next = recursiveInsert(ref int value, ref list.next);
return list;
}
}
How can I modify this method to make the recursive call look like this:
recursiveInsert(value, ref list.next)
instead of:
list.next = recursiveInsert(ref int value, ref list.next);
Upvotes: 0
Views: 325
Reputation: 203827
Since you are never actually mutating the parameters that you are passing by reference, you can just not pass them by reference at all. You need to recognize that MyLinkedList
being a reference type (it should absolutely be a reference type) means that you're not passing the value of the object itself, you're passing a reference to it, so you can mutate that reference without passing the reference by reference.) Just remove all uses of ref
(and also fix your return type to be correct) and you're just done:
public static MyLinkedList recursiveInsert(int value, MyLinkedList list)
{
if (list == null)
return new MyLinkedList(value, null);
else
{
list.next = recursiveInsert(value, list.next);
return list;
}
}
Upvotes: 5