python3:
class Solution: def hasCycle(self , head ): # write code here if not head: return head # 双指针 快慢指针 slow = head fast = head while slow and fast: slow = slow.next if fast.next: fast = fast.next.next else: return False # 当双指针相遇 即表示指针有环 if slow == fast: return True return False
java:
public class Solution { public boolean hasCycle(ListNode head) { if (head == null) return false; //快慢两个指针 ListNode slow = head; ListNode fast = head; while (fast != null && fast.next != null) { //慢指针每次走一步 slow = slow.next; //快指针每次走两步 fast = fast.next.next; //如果相遇,说明有环,直接返回true if (slow == fast) return true; } //否则就是没环 return false; } }
快慢指针问题即可解决,当两个指针相遇,即证明链表有环