Scheme, getting the pointer from pointed struct
Assume I have a such struct:
(define-struct node (value next))
;and making 2 nodes, parent pointing to child as next.
(define child (make-node 2 null))
(define parent (make-node 1 child))
Under PLT Scheme, while having child in my hand (and not knowing that parent is the pointer), is it possible to find the poin开发者_Python百科ting node sctuct without knowing the parent?
No, it is not possible. And in fact, if you don't keep a reference to the parent object around anywhere, the parent object may be garbage collected. Any object which can be proven to never be reachable may be deleted at any time. If you don't store a reference to that object anywhere, then it is not reachable.
Now, there are a couple of options if you really did want to get back to the parents. You could save a reference to your parent in your child node (you would have to set it after creating your parent). A less optimal solution, but one that would work if you can't change the data structures in question for some reason, would be keep a list of all nodes that you create, and then search through that list for one which had a child that was eq?
to the node in question. Or you could do the same, but save them in a hash table, with the key being the child and the value being the parent (or list of parents, if there can be more than one), for greater efficiency. I'm not sure if any of these solutions would work for you, as they may depend on the language level that you are using, if you are doing this in an introductory class and not using the full language.
No, you can't. Where did you even get the idea this might be possible?
精彩评论