ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        // if two linked lists have intersection, thay share the same tail-node.
        
        if (headA == NULL || headB == NULL) {
            return NULL;
        }
        
        ListNode *tailA = headA;
        int lenA = moveToTail(tailA);

        ListNode *tailB = headB;
        int lenB = moveToTail(tailB);
        
        if (lenA > lenB) {
            headA = move(headA, lenA - lenB);
        }
        else {
            headB = move(headB, lenB - lenA);
        }
        
        while (headA != headB) {
            headA = headA->next;
            headB = headB->next;
        }
        
        return headA;
    }
Esempio n. 2
0
 //default need to be implemented
 int get(int key) {
     if(hash.find(key) == hash.end()){//not in the hash table
         return -1;
     }
     else{
         cacheNode* cur = hash[key];
         //remove the node from cur position, and move to the tail
         cur->prev->next = cur->next;
         cur->next->prev = cur->prev;
         moveToTail(cur);
         return cur->val;
     }
 }
Esempio n. 3
0
 //default need to be implemented
 void set(int key, int value) {
     //if(hash.find(key) != hash.end()){
         //hash[key]->val = value; //update
         //hash[key]->prev->next = hash[key]->next;//delete the node from cur position
         //hash[key]->next->prev = hash[key]->prev;
         //moveToTail(hash[key]); //move to tail
     //}
     if(get(key) != -1){//if the node with the same key already in the cache
         hash[key]->val = value;
         return;
     }
     else{
         if(hash.size() == capacity){
             hash.erase(head->next->key); //added a cacheNode(0, 0) as head
             head->next = head->next->next;
             head->next->prev = head;
         }
         cacheNode* node = new cacheNode(key, value);
         hash[key] = node;
         moveToTail(node);
     }
 }