Exposing Node?
Consider the following operation which we have explored earlier:
public void delete(Node<T> target) { }
public void insertAfter(Node<T> target, T data) { }
public void insertBefore(Node<T> target, T data) { }
Exercise How does one get a reference to a node in an arbitrarily position among the nodes in a DLL?
Solution
We can update the get
method to return a reference to a node at the target position.
- public T get(int index) { }
+ public Node<T> get(int index) { }
We can also update the following methods to return a reference to a newly inserted node.
- public void addFirst (T data) { }
+ public Node<T> addFirst (T data) { }
- public void addLast(T data) { }
+ public Node<T> addLast(T data) { }
When we use Node
as a type in the signature of any of the public operations (such as delete
), we must also make Node
available (change it from private
to a public
static nested class).
Exercise What are the potential risks of exposing Node
to clients of DLL?
Solution
A deviant client can change the value stored at a node and/or change the next
/prev
pointers. The latter will corrupt the data structure.