链表的递归插入方法

0 .net c#

我正在学习 C#,并且为链表创建了一个递归插入方法:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

如何修改此方法以使递归调用如下所示:

recursiveInsert(value, ref list.next)
Run Code Online (Sandbox Code Playgroud)

代替:

list.next = recursiveInsert(ref int value, ref list.next);
Run Code Online (Sandbox Code Playgroud)

Ser*_*rvy 5

由于您实际上从未改变通过引用传递的参数,因此您根本不能通过引用传递它们。您需要认识到,MyLinkedList作为引用类型(它绝对应该是引用类型)意味着您没有传递对象本身的值,而是传递对其的引用,因此您可以在不传递对象的情况下改变该引用通过引用进行引用。)只需删除所有使用ref(并修复您的返回类型以使其正确),您就完成了:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)