LeetCode每日一题 141. 环形链表

题目链接LeetCode每日一题 141. 环形链表_第1张图片

思路

快慢指针

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
     
public:
    bool hasCycle(ListNode *head) {
     
        ListNode *l = head;
        ListNode *r = head ? head->next : head;
        while (r && r->next) {
     
            l = l->next;
            r = r->next->next;
            if (l == r) return true;
        }
        return false;
    }
};

你可能感兴趣的:(LeetCode每日一题,双指针,快慢指针)