算法 RingBuffer

https://en.wikipedia.org/wiki/Circular_buffer

接口定义，实际使用应该定义泛型接口

package com.ljw.javatest;

// Ringbuffer is a circle, and has a head and tail.
// When add item, add item at tail, if item's quantity exceed max,
// then delete the head item.
public interface RingBuffer{

//return the oldest item
public Integer getItem();
//delege the oldest item
public void deleteItem();
//return item from head to tail
public Integer[] getAll();
}

链表实现，定义了一个内部类存储节点

package com.ljw.javatest;

class Node{
Integer value;
Node next;
Node(Integer value){
this.value=value;
}
}

private int max;
private int count;
private Node tail;

public RingBufferWithLinked(int max) throws Exception {
if(max<=0){
throw new Exception("invalid max");
}
this.max=max;
this.count=0;
}

@Override
count++;
return;
}

Node temp = new Node(value);

tail.next = temp;
tail = temp;
if (count < max) {
count++;
return;
}

}

@Override
public Integer getItem() {
}
return null;
}

@Override
public void deleteItem() {
return;
}
count--;
if(count==0){
}
}

@Override
public Integer[] getAll() {
return null;
}
Integer[] result=new Integer[count];
int i=0;
while(temp!=null){
result[i++]=temp.value;
temp=temp.next;
}
return result;
}

}

package com.ljw.javatest;

import java.util.List;

public class RingBufferWithArray implements RingBuffer {

public static void main(String[] args) {

}

Integer[] buffer;
int tail;
int max;
int count;

public RingBufferWithArray(int max) throws Exception {
if (max <= 0) {
throw new Exception("invalid max");
}
buffer = new Integer[max];
this.max = max;
count = 0;
tail = -1;
}

@Override
if (count + 1 > max) {
if (head == max - 1) {
} else {
}
} else {
count++;
if (count == 1) {
}
else {
if (tail == max - 1) {
tail = 0;
buffer[tail] = value;
} else {
buffer[++tail] = value;
}
}
}
}

@Override
public Integer getItem() {
return null;
} else {
}
}

@Override
public void deleteItem() {
if (count == 0) {
return;
}
count--;
if (count == 0) {
}
}
}

@Override
public Integer[] getAll() {
return null;
}

Integer[] result = new Integer[count];
for (int i = 0, temp = head; i < count; i++, temp++) {
if (temp == max) {
temp = 0;
}
result[i] = buffer[temp];
}
return result;

}

}

package com.ljw.javatest;

public class App {
public static void main(String[] args) throws Exception {
int max=3;//max=1;
print(rb.getItem()==1);
rb.deleteItem();
print(rb.getItem()==null);

}

Integer[] result=rb.getAll();
for(int i=0;i<max;i++){
}

}

public static void print(Object value){
System.out.println(value);
}
}

posted on 2019-07-10 00:00  Lv Jianwei  阅读(233)  评论(0编辑  收藏

• 随笔 - 78
• 文章 - 2
• 评论 - 4