0

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);
8
  • but why you need "ref value" if noone changes it inside the method, so noone would even read that "changed" value after the call? Commented Jun 10, 2014 at 15:22
  • 2
    Your return signature and your return statements don't all match up. Commented Jun 10, 2014 at 15:29
  • Pass the list by ref and the value as the return value of the function. Also, this will cause a Stackoverflow exception since you never stop recursing. Commented Jun 10, 2014 at 15:32
  • @Gusman It won't create a new list each time a value is added because if the value is added the list is not null thus no new list will be made. Commented Jun 10, 2014 at 15:36
  • Don't you just wanna add a node instead of a linkedlist? Commented Jun 10, 2014 at 15:36

1 Answer 1

5

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.