LeetCode刷题笔记- 141.环形链表
不同速率同赛道相遇方案
C代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
struct ListNode *tf = NULL;
struct ListNode *ts = NULL;
if (head == NULL)
return false;
tf = head;
ts = head->next;
while (1) {
if (tf == NULL)
break;
if (ts == NULL)
break;
if (tf == ts)
return true;
tf = tf->next;
ts = ts->next;
if (ts == NULL)
break;
ts = ts->next;
}
return false;
}
注意点
- 快者与慢者的起跑点初始化需要不同更方便实现;