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) {
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;
}
}