算法第四版1.3背包、队列和栈:习题1.3.40

import edu.princeton.cs.algs4.StdOut;

import java.util.Iterator;
public class MoveToFrontimplements Iterable {
    public static void main(String[]args){
        MoveToFront moveToFront=new MoveToFront<>();
        for (int i=0;i<2*26;i++)
            moveToFront.insert((char)('a'+i%26));
        for (char c:moveToFront)
            StdOut.print(c+" ");
        StdOut.println();
    }

    private DoubleNode first;
    private int N;
    private class DoubleNode{
        Item item;
        DoubleNode prev;
        DoubleNode next;
    }
    public MoveToFront(){
        first=null;
        N=0;
    }
    public boolean isEmpty(){return first==null;}
    public void insert(Item item){
        DoubleNode newfirst=new DoubleNode();
        newfirst.item=item;
        if (isEmpty())
            first=newfirst;
        else {
            DoubleNode current=first;
            while (current!=null){
                if (current.item==item){
                    if (current==first){
                        first=current.next;
                        first.prev=null;
                    }
                    else if (current.next==null)//last{
                    {
                        current.prev.next=null;//delete last
                    }
                    else {
                        current.prev.next = current.next;
                        current.next.prev = current.prev;
                    }
                    N--;
                }
                current=current.next;
            }
            newfirst.next=first;
            first.prev=newfirst;
            first=newfirst;
        }
        N++;
    }
    public Iterator iterator(){
        return new MoveToFrontIterator();
    }
    private class MoveToFrontIterator implements Iterator{
        private DoubleNode current=first;
        public boolean hasNext(){return current!=null;}
        public Item next(){
            Item item=current.item;
            current=current.next;
            return item;
        }
    }
}

 

你可能感兴趣的:(算法第四版1.3背包,队列和栈课后习题)