141.环形链表
所谓环形就是最后元素是否相等
即追赶者,与逃跑者的关系;
使用快慢指针
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
if (head == NULL || head->next == NULL) {
return false;
}
struct ListNode *p = head;
struct ListNode *q = head->next;
while (p != q) {
if (q == NULL || q->next == NULL) {
return false;
}
p = p->next;
q = q->next->next;
}
return true;
}
优化思维
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
struct ListNode *p = head, *q = head;
if (p == NULL) return false;
do {
p = p->next;
q = q->next;
if (q == NULL || q->next == NULL) return false;
q = q->next;
} while (p != q);
return true;
}