142. Linked List Cycle II
Medium
128088FavoriteShare
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.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.
Example 2:
Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.
Example 3:
Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.
Follow up:
Can you solve it without using extra space?
1. 暴力解决:
定义一个时间,遍历链表看看能不能发现null。
2. Set判重:
边遍历边将存入set,并将节点与set 中的数据比较。
时间复杂度O(n);
3. 快慢指针法:
定义两个快慢指针 pFast 和 pSlow,pFast 每次走两步,pSlow 每次走一步,如果 pFast 在循环遍历后为 null,则链表中不存在环。如果 pFast 和 pSlow 相遇则链表中存在环。
/**
* 检查是否存在环形链表
*
* @param head
* @return
*/
public boolean detectLoop(Node head) {
Node pSlow = head, pFast = head;
boolean detectFlag = false;
// 只包含一个结点
if (head.next == null) {
return detectFlag;
}
List<Integer> slowPassNodes = new ArrayList<>();
List<Integer> fastPassNodes = new ArrayList<>();
while (true) {
pSlow = pSlow.next;
pFast = pFast.next.next;
slowPassNodes.add(pSlow.item);
if (pFast != null) {
fastPassNodes.add(pFast.item);
}
if (pFast == null) {
break;
}
if (pSlow == pFast) {
detectFlag = true;
break;
}
}
System.out.println("slow pointer traverse node list: " + slowPassNodes);
System.out.println("fast pointer traverse node list: " + fastPassNodes);
return detectFlag;
}