LeetCode Hot 热题100 算法题 142.环形链表II-算法&测试-medium模式
给定一个链表,返回聊表开始入环到达第一个节点。如果链表无环则返回null。
说明:不允许修改给定的链表。
进阶:你是否可以使用O(1)空间解决此题?
package leetcode.medium;
import java.util.HashSet;
import java.util.Set;
//142.环形链表II
public class Solution142 {
public static void main(String[] args) {
ListNode head = new ListNode(3);
head.next=new ListNode(2);
head.next.next=new ListNode(0);
head.next.next.next=new ListNode(-4);
head.next.next.next.next=head.next;
S142CircularList testCircularList = new S142CircularList();
ListNode start = testCircularList.detectCycle(head);
if (start==null) {
System.out.println("not found");
}else {
System.out.println(start.val);
}
}
}
class S142CircularList{
//法1:需额外空间
public ListNode findCircu(ListNode head) {
Set<Integer> hashSet = new HashSet<Integer>();
ListNode cur = head;
while(cur!=null) {
// if (hashSet.contains(cur.val)) {
// return cur;
// }
// hashSet.add(cur.val);
if (!hashSet.add(cur.val)) {
return cur;
}
cur=cur.next;
}
return null;
}
//法2:快慢指针 空间复杂度O(1)
//快慢指针同时从head出发,只要链表存在环,fast和slow就会在环内某点相遇
//相遇时,让ptr指针从head出发,当ptr与slow相遇时 即到达环开始的节点
public ListNode detectCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
do {
if (head==null || head.next==null) {
return null;
}
slow=slow.next;
fast=fast.next.next;
} while (fast!=slow);
ListNode ptr = head;
do {
ptr=ptr.next;
slow=slow.next;
} while (ptr!=slow);
return ptr;
}
}
参考:
- https://leetcode-cn.com/problems/linked-list-cycle-ii/solution/huan-xing-lian-biao-ii-by-leetcode-solution
- https://leetcode-cn.com/problems/linked-list-cycle-ii/solution/linked-list-cycle-ii-kuai-man-zhi-zhen-shuang-zhi-