假期打卡第八天

同样利用快慢指针完成寻找…

两个指针分别运行x、y,我们可以知道y=2x,如果两个指针相遇,它们之间的路程差是x,也就是慢指针走过的距离。同时这个路程差表示,x刚好是这个环内拥有的元素数量的整数倍,即快指针每运行x路程就一定会回到这个节点,
如果我们让慢指针在第一次相遇时返回起点,重新运行到与快指针相遇,他们将在入环的节点处。

ListNode *detectCycle(ListNode *head) {
    
    
    if(head == NULL) return NULL;
    if(head->next == NULL) return NULL;
    if(head->next == head) return head;
    ListNode *tmp1 = head,*tmp2 = head;
    while(true){
    
    
        if(tmp2->next == NULL || tmp2->next->next == NULL) return NULL;
        tmp1 = tmp1->next;
        tmp2 = tmp2->next->next;
        if(tmp1 == tmp2) break;
    }
    tmp1 = head;
    while(tmp1 != tmp2){
    
    
        tmp1 = tmp1->next;
        tmp2 = tmp2->next;
    }
    return tmp1;
}

两数加和

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    
    
    ListNode *OCC = new ListNode(0);
    ListNode *count1 = l1,*count2 = l2;
    ListNode *tmp = OCC;
    int out = 0;
    while(count1 != nullptr && count2 != nullptr) {
    
    
        tmp->next = new ListNode((count1->val + count2->val + out) % 10);
        tmp = tmp->next;
        out = (count1->val + count2->val + out) / 10;
        count1 = count1->next;
        count2 = count2->next;
    }
    while(count1 != nullptr) {
    
    
        tmp->next = new ListNode((count1->val + out) % 10);
        tmp = tmp->next;
        out = (count1->val + out) / 10;
        count1 = count1->next;
    }
    while(count2 != nullptr) {
    
    
        tmp->next = new ListNode((count2->val + out) % 10);
        tmp = tmp->next;
        out = (count2->val + out) / 10;
        count2 = count2->next;
    }
    if(out != 0) tmp->next = new ListNode(out);
    return OCC->next;
}

猜你喜欢

转载自blog.csdn.net/AgaSS1225/article/details/112759709