DoublyLinkedList code weak reference

In your DoublyLinkedList code, you set prev and next to nil in the remove function. Would changing the class Node definition of previous to weak be equally valid?

My code seems to work but I had to be careful. I had to change

     node.next?.previous = Node(element, previous: node, next: node.next)
     node.next = node.next?.previous

to

     node.next = Node(element, previous: node, next: node.next)
     node.next?.previous = node.next

because the new Node would be deallocated immediately in the first version!!

Hi!

Yes, that is a great observation. In the later chapters that talk about trees, I think the parent is made weak. So the idea is that the parent owns (and maintains lifetime) of the children but not vis-versa.

You can think of a doubly linked list as a degenerate version of a tree when there is exactly one (or no) child.

Great point about ordering. Yes, you always need to maintain at least one strong reference to a reference type or it gets deallocated as you observed. Thanks for the comment! :grinning:

Thanks for your reply. The thing that surprised me was the need to reorder. It suggest that the object get deallocated even before leaving scope. I thought it would have time to assign it and thus be retained by its new owner.
Anyhow, thankfully the compiler is alert to this.
regards