题目链接:https://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9?tpId=188&&tqId=36189&rp=1&ru=/activity/oj&qru=/ta/job-code-high-week/question-ranking
题目描述:
判断给定的链表中是否有环
扩展:
你能给出空间复杂度的解法么?
说明:本题目包含复杂数据结构ListNode,点此查看相关信息
Code:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
*
* @param head ListNode类
* @return bool布尔型
*/
int hasCycle(struct ListNode* head ) {
// write code here
if(head == NULL || head->next == NULL)
return 0;
struct ListNode* pFast = head;
struct ListNode* pSlow = head;
while(pFast != NULL && pFast ->next!=NULL)
{
pFast = pFast->next->next;
pSlow = pSlow->next;
if(pFast == pSlow )
return 1;
}
return 0;
}