前面,咱们实现了链表的 反转 操做,本篇来聊聊,如何检测单链表中的环。html
有两种方法来解决这个问题:git
定义一个Map,当循环遍历Linked List时,依次将Node放入Map中,等到循环到下一轮时,检查Node是否存在于Map中,若存在则表示有环存在。github
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */
public class Solution {
public boolean hasCycle(ListNode head) {
Map map = new IdentityHashMap();
for(ListNode x = head; x != null;){
if(map.containsKey(x)){
return true;
}
map.put(x, null);
x = x.next;
}
return false;
}
}
复制代码
若是有限状态机、迭代函数或者链表上存在环,那么在某个环上以不一样速度前进的2个指针一定会在某个时刻相遇。同时显然地,若是从同一个起点(即便这个起点不在某个环上)同时开始以不一样速度前进的2个指针最终相遇,那么能够断定存在一个环,且能够求出2者相遇处所在的环的起点与长度。数据结构
从Linked List的Head节点出发,咱们定义两个移动指针,一个的移动速度为每次前进一个节点,另外一个每次前进两个节点。而后判断这两个指针移动后的结果是否相等。函数
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
return true;
}
}
return false;
}
}
复制代码
这两种方式的时间复杂度均为O(n),空间复杂度均为O(1).oop