队列是一种线性数据结构。该数据结构遵循执行操作的特定顺序。顺序是先进先出( FIFO )。这意味着队列中最先插入的元素将最先出现,最后插入的元素将最后出现。它是一个有序列表,其中元素的插入是从一端(称为后端)完成的,元素的删除是从另一端(称为前端)完成的。与堆栈类似,可以对队列执行多个操作。当向队列中插入元素时,该操作称为“入队” ;当从队列中删除元素时,该操作称为 “出队”。
重要的是要知道,如果队列大小已满,我们无法插入元素,而当队列本身为空时,我们无法删除元素。如果我们尝试在队列已满后插入元素,则这种情况称为溢出,而如果我们尝试在队列为空后删除元素,则这种情况称为下溢。
我们将队列定义为一个列表,其中对列表的所有添加都在一端进行,而对列表的所有删除都在另一端进行。首先被推入订单的元素,首先对其执行操作。
Queue 中的 Enqueue() 操作将一个元素添加(或存储)到队列末尾。 应采取以下步骤将数据排队(插入)到队列中:
从队列中删除(或访问)第一个元素。执行出队操作的步骤如下:
dequeue(){
// 从队列中移除元素
// 在空队列上调用时返回下溢
if(this.isEmpty()){
console.log("Queue is empty");
return -1;
}
return this.items.shift();
}
// Queue class
class Queue
{
// 数组用于实现队列
constructor()
{
this.items = [];
}
}
class QNode
{
constructor(key)
{
this.key = key;
this.next = null;
}
}
let front = null, rear = null;
LRU是Least Recently Used的缩写,即最近最少使用,是一种常用的页面置换算法,选择最近最久未使用的页面予以淘汰。该算法赋予每个页面一个访问字段,用来记录一个页面自上次被访问以来所经历的时间 t,当须淘汰一个页面时,选择现有页面中其 t 值最大的,即最近最少使用的页面予以淘汰。
---来自百科
package main
import (
"fmt"
"testing"
)
type LRUCache struct {
list []int
csize int
ma map[int]int
}
func (lru *LRUCache) refer(x int) {
if index, ok := lru.ma[x]; !ok {
// 如果存在,比较当前的容量是否已达上限
if len(lru.list) == lru.csize {
// 如果已达上限,则删除栈顶元素
lru.list = lru.list[:lru.csize-1]
}
} else {
// 如果存在, 则删除对应 index 位置的值, 并将期追加到队尾
lru.list = append(lru.list[:index-1], lru.list[index+1:]...)
}
lru.list = append(lru.list, x)
lru.ma[x] = len(lru.list)
}
// 打印 cache 中的元素
func (lru *LRUCache) Display() {
for i := len(lru.list) - 1; i >= 0; i-- {
fmt.Println(lru.list[i])
}
}
// 初始化 lru cache
func NewLRUCache(size int) *LRUCache {
ma := make(map[int]int)
return &LRUCache{
list: []int{},
csize: size,
ma: ma,
}
}
// 测试程序
func Test_NewLRUCache(t *testing.T) {
cache := NewLRUCache(4)
cache.refer(1)
cache.refer(2)
cache.refer(3)
cache.refer(1)
cache.refer(4)
cache.refer(5)
cache.Display()
}
阅读量:1534
点赞量:0
收藏量:0