Algs4-1.3.40前移编码

1.3.40前移编码。从标准输入读取一串字符,使用链表保存这些字符并清除重复字符。当你读取了一个从未见过的字符时,将它插入表头。当你读取了一个重复的字符时,将它从链表中删除并再次插入表头。将你的程序命名为MoveToFront:它实现了著名的前移编码策略,这种策略假设最近访问过的元素很有可能再次访问,因此可以用于缓存、数据压缩等许多场景。
答:
图片
public class MoveToFront<Item>
{
    private int N;
    private Node first;
    //
    private class Node
    {
        Item item;
        Node next;
    }
    //
    public void insertToFirst(Item item)
    {
            Node oldfirst=first;
            first=new Node();
            first.item=item;
            first.next=oldfirst;
            N++;
         
            Node current=first;
            while(current.next!=null)
            {
                if(current.next.item.equals(item))
                {
                    Node repeat=current.next;
                    current.next=current.next.next;
                    repeat.next=null;
                    N--;
                    break;
                }
                current=current.next;
            }
      }
   
    public boolean isEmpty()
    {return N==0;}
   
    public int size()
    {return N;}
   
    public void showAll()
    {
        Node current=first;
        while(current!=null)
        {
            StdOut.print(current.item+" ");
            current=current.next;
        }
    }
   
    public static void main(String[] args)
    {
        MoveToFront<String> list=new MoveToFront<String>();
        while(!StdIn.isEmpty())
        {
            String item=StdIn.readString();
            list.insertToFirst(item);
        }
        //
        list.showAll();
    }//end main
}//end class

原文地址:https://www.cnblogs.com/longjin2018/p/9854324.html