题目:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
给定一个链表,判断它是否有环
拓展:
你能不使用额外空间去解决这个问题吗?
思路:
快慢指针同时从头出发,能相遇则说明有环
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null || head.next == null)
return false;
ListNode fast = head;
ListNode slow = head;
while(fast.next != null && fast.next.next != null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow)
return true;
}
return false;
}
}