简体   繁体   English

链表的递归插入方法

[英]Recursive insert-method for a linked list

I'm learning C# and I've made a recursive insert-method for a linked list: 我正在学习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;
    }
}

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);

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: 您需要认识到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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM