LeetCode:141和142,环形链表之追及相遇和快慢指针的运用

这两个题是相关联的,主要做法为哈希和快慢指针,当然像博主我,不看解析只会O(n^2)的暴力遍历,太惨了,不过,快慢指针还是很好理解的,是一个追及的问题,

目录

题目:

​编辑 快慢指针解法原理:

代码LeetCode:141: 

每日表情包:


题目:

LeetCode:141和142,环形链表之追及相遇和快慢指针的运用_第1张图片

LeetCode:141和142,环形链表之追及相遇和快慢指针的运用_第2张图片 快慢指针解法原理:

LeetCode:141和142,环形链表之追及相遇和快慢指针的运用_第3张图片

代码LeetCode:141: 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
bool hasCycle(struct ListNode *head) {
    struct ListNode* pfast = head, * pslow = head;
    while(pfast && pfast->next){
        pfast = pfast->next->next;
        pslow = pslow->next;
        if(pfast == pslow){
            return true;
        }
    }
    return false;
}

代码LeetCode:142:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode *detectCycle(struct ListNode *head) {
    struct ListNode* pfast = head, * pslow = head;
    while(pfast && pfast->next){
        pfast = pfast->next->next;
        pslow = pslow->next;
        if(pfast == pslow){
            while(pfast != head){
                pfast = pfast->next;
                head = head->next;
            }
            return head;
        }
    }
    return NULL;
}

每日表情包:

LeetCode:141和142,环形链表之追及相遇和快慢指针的运用_第4张图片

点点赞吧 ~ 可怜可怜孩子。 

你可能感兴趣的:(leetcode,链表,算法)