141. 环形链表

    xiaoxiao2022-07-14  140

    141. 环形链表

    通过设置两个指针,分别为快指针和慢指针,快指针每次走两步,慢指针每次走一步,如果没有环,那么快指针必定会指向NULL,从而返回false。如果有环,则快指针必定追上慢指针,从而可以返回true。

    /** * 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 *slow,*fast; slow=head; fast=head; while(fast!=NULL&&fast->next!=NULL){ fast=fast->next->next; slow=slow->next; if(fast==slow) return true; } return false; } };

    执行用时 : 12 ms, 在Linked List Cycle的C++提交中击败了99.28% 的用户 内存消耗 : 9.6 MB, 在Linked List Cycle的C++提交中击败了88.85% 的用户

    最新回复(0)