双指针
#双指针可分为快指针与慢指针
public class Solution {
public boolean hasCycle(ListNode head) {
//先判断链表为空的情况 fast-template
if (head == null)
return false;
//快慢双指针
ListNode fast = head;
ListNode slow = head;
//如果没环快指针会先到链表尾
while (fast != null && fast.next != null) {
//快指针移动两步
fast = fast.next.next;
//慢指针移动一步
slow = slow.next;
//相遇则有环
if (fast == slow)
return true;
}
//到末尾则没有环
return false;
}
}
哈希方法
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode pos = head;
// 哈希表记录访问过的结点
Set<ListNode> visited = new HashSet<ListNode>();
while (pos != null) {
// 判断结点是否被访问
if (visited.contains(pos)) {
return true;
} else {
// 结点记录添加到哈希表中
visited.add(pos);
}
// 遍历
pos = pos.next;
}
return false;
}
}
******HashSet中 hash.contains(v就返回value)-->如果包含这个值true,否则就返回false;
hash.add(value)-->添加元素******