leetcode_141
题目描述
Given a linked list, determine if it has a cycle in it.
Follow up: Can you solve it without using extra space?
思路:
设置两个指针p,q,从头结点开始,p节点每次走一步,q节点每次走两步,如果两个指针会相遇,则为环形链表,如果较快的指针q到达了重点则没有环
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
if(head == NULL) return false;
struct ListNode *p = head, *q = head->next;
while(q && q->next) {
p = p->next;
q = q->next;
q = q->next;
if(p == q) return true;
}
return false;
}