Algs4-1.3.39环形缓冲区
1.3.39环形缓冲区。环形缓冲区,又称环形队列,是一种定长为N的先进先出的数据结构。它在进程间的异步数据传输或记录日志文件时十分有用。当缓冲区为空时,消费者会在数据存入缓冲区前等待;当缓冲区满时,生产者会等待将数据存入缓冲区。为RingBuffer设计一份API并用(回环)数组将其实现。
答:
import java.util.Iterator;
public class RingBuffer<Item> implements Iterable<Item>
{
private Item[] a;
private int N;
private int left;
private int right;
public RingBuffer(int arraryLength)
{
a=(Item[]) new Object[arraryLength];
left=0;
right=0;
N=0;
}
public boolean isEmpty()
{return N==0;}
public boolean isFull()
{return N==a.length;}
public int size()
{return N;}
public void enqueue(Item item)
{
if(isFull()) return;
right++;
if(right==a.length) right=0;
a[right]=item;
if(isEmpty()) left=right;
N++;
}
public Item dequeue()
{
Item item;
if(isEmpty())
{
item=null;
}
else if(size()==1)
{
item=a[left];
N--;
}
else
{
item=a[left];
left++;
if(left==a.length) left=0;
N--;
}
return item;
}
public Iterator<Item> iterator() {return new ListIterator();}
private class ListIterator implements Iterator<Item>
{
private int current=left;
public boolean hasNext(){return current!=right+1;}
public void remove(){}
public Item next()
{
Item item=a[current];
current++;
if(current==a.length) current=0;
return item;
}//end next
}//end class ListIterator
}//end class