LeetCode 141. 环形链表

发布时间 2023-06-30 16:47:39作者: 穿过雾的阴霾

取巧


class Solution {
public:
    const int INF=1e9;
    bool hasCycle(ListNode *head) {
        bool res=false;
        auto p=head;
        while(p)
        {
            if(p->val==INF)
            {
                res=true;
                break;
            }
            p->val=INF;
            p=p->next;
        }
        return res;
    }
};

双指针

/**
 * 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) {
        bool res=true;
        if(head==NULL)  return false;
        auto i=head,j=head;
        do
        {
            i=i->next;
            if(j->next&&j->next->next)  j=j->next->next;
            else
            {
                res=false;
                return res;
            }
        }while(i!=j);
        return res;
    }
};