Suppose that you want to write a method that searches for an
item in a generic DLL and returns the pointer to the target (if
search succeeds) or null (if search fails).
One strategy to improve the performance of the search algorithm is,
whenever you have a successful search, you move the target one step
towards the front of the list. You can implement helper
methods.
Example:
7 <--> 5 <--> 0 <--> 11
Search for 0: SUCCESS!
7 <--> 0 <--> 5 <--> 11
Search for 11: SUCCESS!
7 <--> 0 <--> 11 <--> 5
Search for 6: FAIL!
7 <--> 0 <--> 11 <--> 5
Write the method for this improved search method.
public class DLLNode<T> { public T data; public DLLNode<T> prev, next; public DLLNode(T data, DLLNode<T> prev, DLLNode<T> next) { this.data=data; this.prev=prev; this.next=next; }
The next of the last node will be null, and the prev of the first node will be null.
// moves target one step towards the front of DLL after a successful searches public static DLLNode<T> improvedSearch(T target) { /** COMPLETE THIS METHOD **/ }
public class DLLNode<T> {
public T data;
public DLLNode<T> prev, next;
public DLLNode(T data, DLLNode<T>
prev, DLLNode<T> next) {
this.data =
data;
this.prev =
prev;
this.next =
next;
}
// The next of the last node will be null,
and the prev of the first node will be null.
// moves target one step towards the
front of DLL after a successful searches
public DLLNode<T> improvedSearch(T
target) {
if(data.equals(target))
{
return
this;
}
if(next == null)
{
return
null;
}
return
next.improvedSearch(target);
}
}
**************************************************
Thanks for your question. We try our best to help you with detailed
answers, But in any case, if you need any modification or have a
query/issue with respect to above answer, Please ask that in the
comment section. We will surely try to address your query ASAP and
resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.
Get Answers For Free
Most questions answered within 1 hours.