1. 判断链表是否有环
解法一 哈希表
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null) return false;
Set<ListNode> s = new HashSet<>();
while(head != null){
if(!s.add(head)) return true;
head = head.next;
}
return false;
}
}
解法二(最优解) 快慢指针
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null) return false;
ListNode slowPointer = head;
ListNode fastPointer = head.next;
while(slowPointer != fastPointer){
if(fastPointer == null || fastPointer.next == null)
return false;
slowPointer = slowPointer.next;
fastPointer = fastPointer.next.next;
}
return true;
}
}
2. 获取环的入口节点
题解参考
Java实现
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head == null || head.next == null) return null;
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if(fast == slow) {
fast = head;
while(slow != fast) {
slow = slow.next;
fast = fast.next;
}
return fast;
}
}
return null;
}
}
3. 计算环的长度
- 在解决前两个问题的基础上,此问题变得很简单了
- 参考文章
为什么快慢指针一定会相遇?
|