# LeetCode 142：环形链表 II Linked List Cycle II

2019.07.16 14:26 162浏览

**说明：**不允许修改给定的链表。

Given a linked list, return the node where the cycle begins. If there is no cycle, return `null`.

To represent a cycle in the given linked list, we use an integer `pos` which represents the position (0-indexed) in the linked list where tail connects to. If `pos` is `-1`, then there is no cycle in the linked list.

Note: Do not modify the linked list.

``````输入：head = [3,2,0,-4], pos = 1

``````

``````输入：head = [1,2], pos = 0

``````

``````输入：head = [1], pos = -1

``````

Follow-up: Can you solve it without using extra space?

### 哈希表解题：

Java：

``````public class Solution {
if (head == null) return null;//如果是空链表直接返回
Set<ListNode> nodeSet = new HashSet<>();//构造哈希表
}
return null;
}
}
``````

Python：

``````class Solution(object):
"""
:rtype: ListNode
"""
return None
hashSet=set()#构造集合
return None
``````

### 双指针解题：

Java：

``````public class Solution {
return null;
}
while (fast != null && fast.next != null) {//快指针及其下一位是否为null
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {//如果相同，存在环形链表
while (slow != fast) {//继续遍历，再次相遇时的节点即为入环节点
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
return null;
}
}
``````

Python：

``````class Solution(object):
"""
:rtype: ListNode
"""
return None
while fast is not None and fast.next is not None:
slow, fast = slow.next, fast.next.next
if slow == fast:
while slow != fast:
slow = slow.next
fast = fast.next
return slow
return None
``````

0人点赞

• 推荐
• 评论
• 收藏
• 共同学习，写下你的评论

0/150