File tree Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Original file line number Diff line number Diff line change
1
+ // 自己写的一个链表,以time limited 告终,同时里面的一些逻辑还不是很正确
2
+ 1) 对于相同key的catch 如何处理的:更新对应的值
3
+ 2) 只要get 就相当于 最近一次的访问,要将节点提前
4
+ class LRUCache{
5
+ private:
6
+ struct CatchNode{
7
+ int key;
8
+ int value;
9
+ CatchNode *next;
10
+ CatchNode (int x,int y):key(x),value(y),next(NULL){};// 初始化列表
11
+ };
12
+ CatchNode *head;
13
+ public:
14
+ LRUCache(int capacity) {
15
+ head = new CatchNode(capacity,0);// 头结点存放容量和当前长度;
16
+
17
+ }
18
+
19
+ int get(int key) { // 当有相同的key 取哪个呢?从经常使用的开始查找,错了,是进行更新然后作为最近使用的节点
20
+ CatchNode *p = head,*pre = head,*temp = head->next;
21
+ int curLen = head->value;
22
+ while(curLen--)
23
+ {
24
+ pre = p;
25
+ p=p->next;
26
+ if(p && p->key == key) // 这里要判断p 是否为null
27
+ {
28
+ pre = p->next; //
29
+ head->next = p;
30
+ p->next = temp;
31
+ return p->value;
32
+ }
33
+ }
34
+ return -1;
35
+
36
+ }
37
+
38
+ void set(int key, int value) {
39
+ CatchNode *p = head;
40
+ CatchNode *newCatch = new CatchNode(key,value);
41
+ int curLen = head->value;
42
+ /*while(curLen --)
43
+ {
44
+ p=p->next;
45
+ if(p->key == key)
46
+ return;
47
+ }*/ // 不要往后面插入,往前面插,用头插法。越靠近头结点越是最近使用的
48
+ CatchNode *temp = p->next;
49
+ p->next = newCatch;
50
+ newCatch->next = temp;
51
+ if(curLen < head->key)
52
+ head->value += 1;
53
+ else
54
+ {
55
+ CatchNode *pre = p;
56
+ while(curLen --)
57
+ {
58
+ pre = p;
59
+ p = p->next;
60
+ }
61
+ pre->next = NULL;
62
+ }
63
+
64
+ }
65
+ };
You can’t perform that action at this time.
0 commit comments