I've had a question to doubly linked lists in Java yesterday, and there was a confusing comment to this part of my code
public ADList<K,D> split(K key){
// caching the current list
ADList<K, D> temp = this;
// looking for the key k to be split on
while(temp.head.key != key && temp.head.succ != null){
temp.head = temp.head.succ;
}
...
}
Here, I've saved the current instance of the doubly linked list which the method is called on, to look for the node with the key that is passed to the function. I've done this so that the list of the current instance does not get modified.
But I was told that this is wrong, and that the copy temp is not really a copy of the list, but actually a copy of the pointer to the list of the current instance. Which would mean that the function would alter the current instance instead of the copy.
Am I wrong, or has that person confounded Java with C? (lol) I'd really appreciate some insight :) thanks a bunch!
You're in fact storing a reference to the current list. So now changes to temp will affect this, and your method will alter the original list. Just think of:
ADList<K, D> temp = this;
as storing a reference to the list, not the list itself.
Same thing when you do:
ADList<K, D> list = ...
ADLlist<K, D> temp = list; // not a copy, both refer to the same list object
If you want to make a copy, you'd have to implement your own mechanism, such as using a copy constructor:
ADList<K, D> temp = new ADList<>(this);
The contructor would do whatever it's necessary to create an ADList with the same content of the list passed to its argument. This probably means creating new Node objects internally for each Node with the same data in them.
Given the problem you're solving, it seems you want to split a linked list on a given key. It's much better then to operate at the Node level. You can traverse your original list (i.e. this) without modifying it. Then create new nodes for the left and right sublists (see Divide a linked list into half and return the second half for an example).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With