142.环形链表

题目要求

给定一个链表的头节点 head ,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。

如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。

不允许修改 链表。

样例 #1

输入#1

1
head = [3,2,0,-4], pos = 1

输出#1

1
返回索引为 1 的链表节点

解释#1

1
链表中有一个环,其尾部连接到第二个节点。

样例 #2

输入#2

1
head = [1,2], pos = 0

输出#2

1
返回索引为 0 的链表节点

解释#2

1
链表中有一个环,其尾部连接到第一个节点。

样例 #3

输入#3

1
head = [1], pos = -1

输出#3

1
返回 null

解释#3

1
链表中没有环。

提示

链表中节点的数目范围在范围 [0, 104] 内
-105 <= Node.val <= 105
pos 的值为 -1 或者链表中的一个有效索引

解法1

解题思路

从第一个节点开始,找他前面的所有节点地址,如果与当前节点地址相同,则有环,若当前节点为空,则证明无环

缺点:费时费地

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
struct ListNode *detectCycle(struct ListNode *head) {
struct ListNode* past;
struct ListNode* current = head;
int len, i;
for (len = 0; current != NULL; len ++,current = current->next, past = head){
for (i = 0; i < len; i++, past = past->next){
if (current == past)
return past;
}
}
return NULL;
}

解法2

解题思路

利用数学知识求解,运用快慢指针的方法,分别定义 fast 和 slow指针,从头结点出发,fast指针每次移动两个节点,slow指针每次移动一个节点,如果 fast 和 slow指针在途中相遇 ,说明这个链表有环。
若有环,从头结点出发一个指针,从相遇节点 也出发一个指针,这两个指针每次只走一个节点, 那么当这两个指针相遇的时候就是 环形入口的节点

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
ListNode *detectCycle(ListNode *head) {
ListNode* fast = head;
ListNode* slow = head;
while(fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
// 快慢指针相遇,此时从head 和 相遇点,同时查找直至相遇
if (slow == fast) {
ListNode* index1 = fast;
ListNode* index2 = head;
while (index1 != index2) {
index1 = index1->next;
index2 = index2->next;
}
return index2; // 返回环的入口
}
}
return NULL;
}