固定长度活跃记录链表
这篇博客具体的描述了一个数据结构,这个数据结构我暂且命名为固定长度活跃记录链表。
链表大致的作用机理
- 维系一个固定数量的活跃记录链表,最新插入的记录在表头,记录越活跃就越靠前,当记录长度超过固定长度,会将新记录插入,把尾记录丢掉,达到维持固定长度的目的。
- 当一个新的记录插入,链表中如果存在一个记录所含的值与新记录相同,则更新该记录的值并移动到头节点,其他的记录按顺序后移。
我的实际场景是,需要存储键值对,为了方便,我将Node当中的值定位String,以冒号将键和值隔开。
存储 数据结构为 键 + :+值
获取 输入 键
得到 值
链表是双向链表结构,即一个节点有头指针和尾指针。
public static class FixedActiveList{
private static class Node {
String item;
Node next;
Node prev;
Node(Node prev, String element, Node next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
private Node head;
private Node tail;
private int capacity;
private int len;
/**
* 初始化
* @param capacity 固定长度
*/
public FixedActiveList(int capacity){
this.capacity = capacity;
}
/**
* 添加元素
* 从头开始遍历表
* 含有元素,则调到头,其余顺序后移
*/
public void add(String item)
{
String index = item.substring(0, item.indexOf(':'));
if(head != null)
{
Node tmp = head;
while (tmp != null)
{
if(tmp.item.startsWith(index))
{//存在对应记录
tmp.item = item;
if(tmp.prev != null)
{//非头
//将旧记录活跃成头节点,其余顺序下移
if(tmp.next == null)//是尾
tail = tmp.prev;
else
tmp.next.prev = tmp.prev;
tmp.prev.next = tmp.next;
tmp.next = head;
head.prev = tmp;
head = tmp;
tmp.prev = null;
}
break;
}
tmp = tmp.next;
}
if(tmp==null)
{//没有匹配项
Node node = new Node(null, item, head);
head.prev = node;
head = node;
if(len == capacity)
{//固定列表长度
tail = tail.prev;
tail.next = null;
}else {
len++;
}
}
}else
{//第一个元素的插入
head = new Node(null, item, null);
tail = head;
len++;
}
}
/**
* 查询元素
*/
public String get(String index)
{
Node tmp = head;
String result = "No cache here please clear cache";
while (tmp != null)
{
if(tmp.item.startsWith(index))
{
result = tmp.item.substring(tmp.item.indexOf(':')+1);
break;
}
tmp = tmp.next;
}
return result;
}
}
测试案例
@Test
public void test()
{
FixedActiveList fixedActiveList = new FixedActiveList(5);
fixedActiveList.add("index1:1-2");
fixedActiveList.add("index2:1-2");
fixedActiveList.add("index3:1-2");
fixedActiveList.add("index4:1-2");
fixedActiveList.add("index5:1-2");
fixedActiveList.add("index5:2-2");
fixedActiveList.add("index1:1-21");
fixedActiveList.add("index3:2-2");
fixedActiveList.add("index6:1-2");
fixedActiveList.add("index7:1-2");
System.out.println(fixedActiveList.get("index1"));
System.out.println(fixedActiveList.get("index2"));
System.out.println(fixedActiveList.get("index3"));
System.out.println(fixedActiveList.get("index4"));
System.out.println(fixedActiveList.get("index5"));
System.out.println(fixedActiveList.get("index6"));
System.out.println(fixedActiveList.get("index7"));
}
创作不易,谢谢支持!