1. 题目描述
给定一个链表的头节点 head ,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。
不允许修改 链表。
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:返回索引为 1 的链表节点
解释:链表中有一个环,其尾部连接到第二个节点。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/linked-list-cycle-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.解题思路
2.1 本人解题思路
/**
* 将每个结点放入set中对结点进行遍历,当再次遇到相同的结点时,那么该结点即为入环的第一个结点
*
*/
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode pos = head;
Set<ListNode> visited = new HashSet<ListNode>();
while (pos != null) {
if (visited.contains(pos)) {
return pos;
} else {
visited.add(pos);
}
pos = pos.next;
}
return null;
}
}
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
# rec, node = set(),head
rec = set()
node = head
"""
python while语法
- 定义多个变量 变量1,变量2 = 值1, 值2
- while 循环: while node: 当node不为None时
- 判断变量不存在,返回Node if not node:return Node
- python创建一个set, 变量名 = set()
"""
while node:
if node in rec:
return node
rec.add(node)
node = node.next
return None
2.2 官方答题-快慢指针法
/**
* 第一次相遇:fast步长为2,slow步长为1.fast==slow相遇时,将fast的步长也设为1,并且fast执行head结点
* 第二次相遇:fast步长为1,slow步长为1,当fast和slow再次相遇时,相遇结点即为入环的第一个结点
*
*/
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
if (head == null) {
return null;
}
ListNode fast = head, slow = head;
// 找出fast和slow第一次相遇的节点
while (fast != null) {
slow = slow.next;
if (fast.next != null)
fast = fast.next.next;
else
return null;
if (slow == fast)
break;
}
// fast从头结点开始,slow继续向前进
// fast和slow再次相遇的节点就是入环的第一个节点
ListNode pstr = head;
while(pstr != slow) {
pstr = pstr.next;
if (null != slow)
slow = slow.next;
}
return pstr;
}
}