题解 | #判断链表中是否有环#
判断链表中是否有环
https://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
/** * 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) { if(head==NULL) return false; ListNode * fast = head -> next; ListNode * low = head; while(fast !=NULL and low != NULL){ if(fast == low){ return true; }else{ if(fast->next!=NULL and fast->next->next!=NULL){ fast = fast ->next->next; low = low ->next; }else{ return false; } } } return false; } };
看了题解,这里很巧妙用了 一个fast 走的比low快,解决了空间复杂度问题,当fast追上low的时候,就说明有环,没有就正常退出