注:此博客不再更新,所有最新文章将发表在个人独立博客limengting.site。分享技术,记录生活,欢迎大家关注
题目描述
一个链表中包含环,请找出该链表的环的入口结点。
方法一:空间复杂度O(n)
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
import java.util.HashSet;
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead)
{
// 1、head作为key放入hashset,只有key,没有value,空间复杂度O(n)
if (pHead == null) return null;
HashSet<ListNode> set = new HashSet<>();
while (pHead != null) {
if (!set.add(pHead)) {
return pHead;
}
pHead = pHead.next;
}
return null;
}
}
方法二:空间复杂度O(1)
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead)
{
// 2、不使用辅助空间
// 快指针一次走两步,慢指针一次走一步,如果快指针遇到空则返回无环
// 如果有环则快指针和慢指针一定会相遇,相遇后快指针回到开头,以后快指针和慢指针都一次走一步,相遇处即为入环节点
if (pHead == null || pHead.next == null) return null;
ListNode fast = pHead.next.next;
ListNode slow = pHead.next;
while (fast != slow) {
if (fast == null || fast.next == null) {
return null;
}
slow = slow.next;
fast = fast.next.next;
}
fast = pHead;
while (fast != slow) {
slow = slow.next;
fast = fast.next;
}
return fast;
}
}