LeetCode热题100道-Day06
- 使用快慢指针,快指针每次前进两个单位,慢指针前进一个单位,如果是环,最终会相遇。
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
if(head == null){
return false;
}
while(true){
if(fast.next == null || fast.next.next ==null){
return false;
}
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
return true;
}
}
}
}
func hasCycle(head *ListNode) bool {
if head == nil {
return false
}
fast := head
slow := head
for ;; {
if fast.Next == nil || fast.Next.Next == nil {
return false
}
fast = fast.Next.Next
slow = slow.Next
if fast == slow{
return true
}
}
}