Swift 3从单链表中删除节点

时间:2021-01-10 07:16:32

I am trying to remove all elements from a linked list of integers that have value val. Is it necessary to set the removed nodes to nil to free memory?

我试图从具有值val的整数链接列表中删除所有元素。是否有必要将删除的节点设置为nil以释放内存?

func removeElements(_ head: Node?, _ val: Int) -> Node? {
    var first = head
    var current = head
    var prev: Node?
    while current != nil {
        if current?.val != val {
            prev = current
        } else if current?.val == first?.val {
            var oldFirst = first
            first = current?.next
            oldFirst = nil // is this line necessary?
        } else {
            prev?.next = current?.next // do I need to set current to nil?
        }
        current = current?.next
    }
    return first
}

1 个解决方案

#1


1  

oldFirst = nil only sets the variable in your current scope to nil.
Again, current is a variable in your local scope, it gets already dereferenced and thus cleaned up once you leave its scope.

oldFirst = nil仅将当前范围中的变量设置为nil。同样,current是本地范围中的变量,它已经被解除引用,因此一旦离开其范围就会被清除。

If you have no strong references to an object anymore it is released by itself because Swift uses Automatic Reference Counting (ARC: https://en.wikipedia.org/wiki/Automatic_Reference_Counting)

如果您对对象没有强引用,则它会自行释放,因为Swift使用自动引用计数(ARC:https://en.wikipedia.org/wiki/Automatic_Reference_Counting)

I am not sure why you have the 2nd case in your code. I guess it checks the case where the current node has value val but you compare to first.val instead of val

我不知道为什么你的代码中有第二个案例。我猜它会检查当前节点有值val的情况,但你比较first.val而不是val

#1


1  

oldFirst = nil only sets the variable in your current scope to nil.
Again, current is a variable in your local scope, it gets already dereferenced and thus cleaned up once you leave its scope.

oldFirst = nil仅将当前范围中的变量设置为nil。同样,current是本地范围中的变量,它已经被解除引用,因此一旦离开其范围就会被清除。

If you have no strong references to an object anymore it is released by itself because Swift uses Automatic Reference Counting (ARC: https://en.wikipedia.org/wiki/Automatic_Reference_Counting)

如果您对对象没有强引用,则它会自行释放,因为Swift使用自动引用计数(ARC:https://en.wikipedia.org/wiki/Automatic_Reference_Counting)

I am not sure why you have the 2nd case in your code. I guess it checks the case where the current node has value val but you compare to first.val instead of val

我不知道为什么你的代码中有第二个案例。我猜它会检查当前节点有值val的情况,但你比较first.val而不是val