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

本文介绍了一个名为MoveToFront的泛型算法实现,该算法通过将访问过的元素移到双向链表的前端来优化数据访问效率。代码示例展示了如何使用Java创建双向链表,插入元素,并通过迭代器遍历链表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import edu.princeton.cs.algs4.StdOut;

import java.util.Iterator;
public class MoveToFront<Item>implements Iterable<Item> {
    public static void main(String[]args){
        MoveToFront<Character> 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<Item> iterator(){
        return new MoveToFrontIterator();
    }
    private class MoveToFrontIterator implements Iterator<Item>{
        private DoubleNode current=first;
        public boolean hasNext(){return current!=null;}
        public Item next(){
            Item item=current.item;
            current=current.next;
            return item;
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值