链表特点
链表通过指针将零散的内存块串联在一起,把内存块成为节点;
存储时不需要连续的空间;
链表的形式有:单向链表、双向链表、循环链表
双向链表实现代码
package com.algorithm.linked;
/**
* 双向链表实现
*/
public class LinkedListTest {
private MyNode head;
private MyNode tail;
private int size;
public LinkedListTest(){};
public static class MyNode{
private String data;
private MyNode next;
private MyNode prev;
public MyNode(String data, MyNode next, MyNode prev){
this.data = data;
this.next = next;
this.prev = prev;
}
}
public synchronized boolean addHeadNode(String data){
if(data == null || data.length() == 0){
return false;
}
if(this.head == null && this.tail == null){
MyNode head = new MyNode(data, null, null);
this.head = head;
this.tail = head;
this.size++;
return true;
}
this.head = new MyNode(data, this.head, null);
head.next.prev = this.head;
this.size++;
return true;
}
public synchronized boolean addTailNode(String data){
if(data == null || data.length() == 0){
return false;
}
if(this.head == null && this.tail == null){
MyNode head = new MyNode(data, null, null);
this.head = head;
this.tail = head;
this.size++;
return true;
}
MyNode tail = new MyNode(data, null, this.tail);
this.tail.next = tail;
this.tail = tail;
this.size++;
return true;
}
public synchronized boolean addRandomNode(int index, String data){
if(index < 1 || index > this.size){
return false;
}
MyNode node = this.head;
for(int i = 1; i < index; i++){
node = node.next;
}
node.next = new MyNode(data, node.next, node);
return true;
}
public synchronized boolean deleteHead(){
MyNode next = this.head.next;
next.prev = null;
this.head = next;
return true;
}
public synchronized boolean deleteTail(){
MyNode prev = tail.prev;
prev.next = null;
this.tail = prev;
return true;
}
public void print(){
MyNode node = this.head;
while (true){
if(node == null){
return;
}
System.out.println(node.data);
node = node.next;
}
}
public static void main(String[] args) {
LinkedListTest linkedListTest = new LinkedListTest();
linkedListTest.addHeadNode("1");
linkedListTest.addHeadNode("2");
linkedListTest.addHeadNode("3");
linkedListTest.addRandomNode(1, "4");
linkedListTest.deleteHead();
linkedListTest.print();
}
}
链表实现LRU算法
LRU算法中文全称 最近最少使用
实现思想:
1、判断链表中是否存在,当前请求的数据,如果存在则删除链表中的数据(如果数据是非头结点的话),删除后将请求数据放到头结点;
2、判断当前请求数据不存在链表中,再校验链表大小是否已满,如果已满则删除末尾数据;将最新请求数据插入头结点;