Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
/**
* 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 *p=head, *q=head;
while (q && q->next){
p = p->next;
q = q->next->next;
if (q == p)
return true;
}
return false;
}
};

本文将介绍一种不使用额外空间的方法来判断给定链表中是否存在环,并通过定义链表节点结构,实现循环判断逻辑。

334

被折叠的 条评论
为什么被折叠?



