URLCatche缓存机制-前端实现

今天是学习前端的第391天,学习了一下在牛客看到同学的URLCatche缓存写的十分的有意思就研究了一下,并可以加强我们对指针的学习。

URLCatche大概含义就是个具有一定长度的储存卡,首先设置上长度size,存储put的长度超过限制后会将最开始存储的数据删除掉,获取get数据后数据会放到首位。

这是一个空URLCatche

在这里插入图片描述

存入一条数据后

在这里插入图片描述

使用

在这里插入图片描述

源码放在下面:

class ListNode {
  constructor(key, val) {
    this.key = key
    this.val = val
    this.pre = null
    this.next = null
  }
}

var LRUCache = function (capacity) {
  this.size = capacity
  this.map = new Map()
  this.head = new ListNode(null, null)
  this.tail = new ListNode(null, null)
  this.head.next = this.tail
  this.tail.pre = this.head
}

LRUCache.prototype.get = function (key) {
  if (!this.map.has(key)) return -1
  const val = this.map.get(key).val
  this.put(key, val)
  return val
}

LRUCache.prototype.put = function (key, value) {
  if (!this.map.has(key)) {
    if (this.map.size === this.size) {
      let node = this.tail.pre
      const k = node.key
      this.tail.pre = node.pre
      node.pre.next = this.tail
      node.pre = null
      node.next = null
      node = null
      this.map.delete(k)
    }
    const node = new ListNode(key, value)
    node.next = this.head.next
    node.pre = this.head
    node.next.pre = node
    node.pre.next = node
    this.map.set(key, node)
  } else {
    const node = this.map.get(key)
    node.val = value
    if (node.pre !== this.head) {
      node.pre.next = node.next
      node.next.pre = node.pre
      node.pre = this.head
      node.next = this.head.next
      node.pre.next = node
      node.next.pre = node
    }
  }
}
const cache = new LRUCache(2)
cache.put('a', 123)
cache.put('b', 456)
cache.put('c', 789)

照抄自:牛客同学货拉拉面经
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值