[刷题记录4]环形链表 ll 与证明
题目信息:
给定一个链表的头节点 head ,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。
不允许修改 链表。
题目参考:
力扣:142. 环形链表 II
题目思路(环境来自力扣OJ的C语言):
1.使用快慢指针找到两指针相遇的地方,记录为find指针。
2.新指针tHead 指向 头结点Head,find 和 tHead 同速,最后相遇时就是 开始入环的第一个节点。
复杂度:
时间复杂度:O(n)
空间复杂度:O(1)
代码和解释:
1.使用快慢指针找到两指针相遇的地方,记录为find指针。
struct ListNode *detectCycle(struct ListNode *head) {
struct ListNode* slow = head;
struct ListNode* fast = head;
bool is_circle = false; // 检查是否为环
while (fast && fast->next) // 3.当 fast、fast->next 有一个为空则退出循环
{
slow = slow->next; // 1.使用快慢指针,fast 走两步,slow 走一步
fast = fast->next->next;
if (slow == fast) // 2.当 fast 和 slow 相遇时说明有环。
{
is_circle = true;
break;
}
}
if (is_circle == false) // 不为环直接退出
return NULL;
}
解释可参考:(刷题记录3)环形链表与证明
2.新指针tHead 指向 头结点Head,find 和 tHead 同速,最后相遇时就是 开始入环的第一个节点。
struct ListNode* tHead = head; // 从头节点开始移动
struct ListNode* find = slow; // 从 fast 和 slow 相遇开始移动
while (tHead != find) // 同速移动,相等退出
{
tHead = tHead->next;
find = find->next;
}
return find;
完整代码:
struct ListNode *detectCycle(struct ListNode *head) {
struct ListNode* slow = head;
struct ListNode* fast = head;
bool is_circle = false; // 检查是否为环
while (fast && fast->next) // 3.当 fast、fast->next 有一个为空则退出循环
{
slow = slow->next; // 1.使用快慢指针,fast 走两步,slow 走一步
fast = fast->next->next;
if (slow == fast) // 2.当 fast 和 slow 相遇时说明有环。
{
is_circle = true;
break;
}
}
if (is_circle == false) // 不为环直接退出
return NULL;
struct ListNode* tHead = head; // 从头节点开始移动
struct ListNode* find = slow; // 从 fast 和 slow 相遇开始移动
while (tHead != find) // 同速移动,相等退出
{
tHead = tHead->next;
find = find->next;
}
return find;
}