题解 | #判断链表中是否有环#
判断链表中是否有环
http://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
快慢指针,如果有环的话,快指针和慢指针最终会相遇。while循环条件是快指针的条件,快指针会移动得快一些,如果判断慢指针的条件,则快指针处就可能出现段错误了。
/**
* 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)
return false;
ListNode* p_slow = head;
ListNode* p_fast = head;
while(p_fast && p_fast->next)
{
p_slow = p_slow->next;
p_fast = p_fast->next->next;
if(p_slow == p_fast)
return true;
}
return false;
}
};
查看5道真题和解析