算法第四版 练习 1.3.39

RingBuffer.java

public class RingBuffer {
    private Item[] item;
    private int read;
    private int write;
    public RingBuffer(int cap)
    {
        item = (Item[])(new Object[cap]);
        write = 0;
        read = 0;
    }
    public boolean isEmpty()
    {
        return write == read;
    }
    public boolean isFull()
    {
        return write < read;
    }
    public int size()
    {
        return item.length;
    }
    public void put(Item data)
    {
        if (!isFull())
            read = write;
        item[write] = data;
        write = ++write % size();
    }
    public Item get()
    {
        if (isEmpty())
            return null;
        Item ret = item[read];
        write = read;
        item[read--] = null;
        return ret;
    }
}

main.java

import edu.princeton.cs.algs4.StdOut;

public class Main {
    public static void main(String[] args)
    {
        RingBuffer rb = new RingBuffer(5);
        for (int i = 0; i < 5; ++i)
            rb.put(i);
        for (int i = 5; i < 7; ++i)
            rb.put(i);
        for (int i = 0; i < 5; ++i)
            StdOut.print(rb.get() + " ");
    }
}

运行结果:

算法第四版 练习 1.3.39_第1张图片

你可能感兴趣的:(算法第四版)