标签:style blog http color os 数据 for ar
struct Node { int key; Node* next; Node* pre; }; class LRUCache{ private: Node *head,*tail; int CatcheSize=0,capacity=0; map<int,int> m1; public: LRUCache(int capacity) { this->capacity = capacity; head = tail = 0; CatcheSize = 0; } int get(int key) { map<int,int>::iterator it; it = m1.find(key); if(it == m1.end())//如果没有找到,则返回-1 return -1; //找到了,将其移入末尾 Node* tmp = head; for (int i=0;i<CatcheSize;i++) { if(key == tmp->key ) { if(head != tail) { if(tmp == head) { head = head->next; head ->pre =0; tail ->next = tmp; tmp ->pre = tail; tail = tmp; tail ->next = 0; } else if(tmp != tail) { tmp ->pre ->next = tmp -> next; tmp ->next ->pre = tmp ->pre; tail -> next = tmp; tmp -> pre = tail; tail = tmp; tail -> next = 0; } } break; } tmp = tmp->next; } return m1[key]; } void set(int key, int value) { int i=0; //遍历链表,查看这个键是否存在,若存在,则更新其值; //否则,插入改组数据。最后将该键数据移到链表尾部。 Node* tmp = head; for ( i=0;i<CatcheSize;i++) { if(key == tmp->key ) { m1[key] = value; if(head != tail) { if(tmp == head) { head = head->next; head ->pre =0; tail ->next = tmp; tmp ->pre = tail; tail = tmp; tail ->next = 0; } else if(tmp != tail) { tmp ->pre ->next = tmp -> next; tmp ->next ->pre = tmp ->pre; tail -> next = tmp; tmp -> pre = tail; tail = tmp; tail -> next = 0; } } break; } tmp = tmp->next; } //如果链表中不存在该键则新建节点,并链入表尾。 if(i == CatcheSize || CatcheSize == 0) { m1[key] = value; Node* tmp1 = new Node; tmp1 ->key = key; CatcheSize++; if(head != 0) { tail -> next = tmp1; tmp1 -> pre = tail; tail = tmp1 ; tail ->next =0; } else { head = tmp1; tail = tmp1; tail ->next = 0; head ->next = 0; tail ->pre = 0; } } //如果空间已满,则删除头结点 if(CatcheSize > capacity) { Node* fre; fre = head; m1.erase(fre -> key); if(head != tail) head = head ->next; else { head = 0; tail = 0; } delete [] fre; CatcheSize--; } } };
标签:style blog http color os 数据 for ar
原文地址:http://www.cnblogs.com/ZhangYushuang/p/3906910.html