*JAVA* If the order that items in a list are stored is not important, you can fr
ID: 3741309 • Letter: #
Question
*JAVA*
If the order that items in a list are stored is not important, you can frequently speed searching with the heuristic known as move to front: Whenever an item is accessed, move it to the front of the list. This action usually results in an improvement because frequently accessed items tend to migrate toward the front of the list, whereas less frequently accessed items tend to migrate toward the end of the list. Consequently, the most frequently accessed items tend to require the least searching. Implement the move-to-front heuristic for linked lists.
Explanation / Answer
public class LinkedList
{
class Node
{
int key;
Node next;
}
private Node head=null;
public LinkedList Move(LinkedList ls,int key)
{
Node prev=null;
Node curr=ls.head;
while(curr!=null)
{
if(prev!=null && curr.key==key)
{
prev.next=curr.next;
curr.next=ls.head;
ls.head=curr;
}
prev=curr;
curr=curr.next;
}
return ls;
}
}
Do give a thumbs up
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.