LinkedList
public class LinkedList<T> {
//記錄頭部節點
public Node list;
//記錄鏈表大小
public int size;
//添加節點放在頭部
public void put(T data) {
Node headNode = list;
Node currentNode = new Node(data, headNode);
list = currentNode;
size++;
}
//根據指定位置添加
public void put(int index, T data) {
//判斷下標是否越界
testingIndex(index);
//這是頭部節點
Node headNode = list;
Node currentNode = list;
for (int i = 0; i < index; i++) {
headNode = currentNode;
currentNode = currentNode.next;
}
Node node = new Node(data, currentNode);
headNode.next = node;
size++;
}
//刪除頭部節點
public T remove() {
if (list != null) {
Node node = list;
list = list.next;
node.next = null;
size--;
return list.data;
}
return null;
}
//根據下標刪除節點
public T remove(int index) {
testingIndex(index);
Node headNode = list;
Node currentNode = list;
for (int i = 0; i < index; i++) {
headNode = currentNode;
currentNode = currentNode.next;
}
headNode.next = currentNode.next;
currentNode.next = null;
size--;
return currentNode.data;
}
//刪除尾部節點
public T removeLast() {
if (list != null) {
Node headNode = list;
Node currentNode = list;
while (currentNode.next != null) {
headNode = currentNode;
currentNode = currentNode.next;
}
headNode.next = null;
size--;
return currentNode.data;
}
return null;
}
//修改節點
public void set(int index, T data) {
testingIndex(index);
Node currentNode = list;
for (int i = 0; i < index; i++) {
currentNode = currentNode.next;
}
currentNode.data = data;
}
//查詢節點
public T get(int index) {
Node headNode = list;
for (int i = 0; i < index; i++) {
headNode = list.next;
}
return headNode.data;
}
public void testingIndex(int index) {
if (!(index >= 0 && index <= size)) {
throw new IndexOutOfBoundsException("index:" + index + "size:" + size);
}
}
public void toStirng() {
for (int i = 0; i < size; i++) {
System.out.println(list.data);
list = list.next;
}
}
//節點類
class Node {
private T data;
private Node next;
public Node(T data, Node next) {
this.data = data;
this.next = next;
}
}
}
什麼是LRU算法
代碼裏有註釋
public class LruLinkedList<T> extends LinkedList<T> {
/**
* lru算法
* 新增的數據放在頭部,添加的時候超過了內存大小,就刪除尾部
* 緩存命中,即緩存數據被訪問時移至頭部,
*/
public static final int defaultSize = 5;
public int lruSize;
public LruLinkedList() {
this(defaultSize);
}
public LruLinkedList(int size) {
this.lruSize = size;
}
//增
public void lruPut(T data) {
if (size >= lruSize) {
removeLast();
put(data);
} else {
put(data);
}
}
//刪
public void lruRemove() {
removeLast();
}
//改
public void lruSet(int index, T data) {
testingIndex(index);
Node head = list;
Node cur = list;
for (int i = 0; i < index; i++) {
head = cur;
cur = cur.next;
}
head.next = cur.next;
cur.next=list;
cur.data=data;
list=cur;
}
//查
public void lruGet(int index) {
testingIndex(index);
Node head = list;
Node cur = list;
for (int i = 0; i < index; i++) {
head = cur;
cur = cur.next;
}
head.next = cur.next;
cur.next=list;
list=cur;
}
}
學習算法與數據結構中,作爲學習筆記記錄
,測試問題不大,希望有大神指點,謝謝