Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
链表中的Two Pointers是一种很常用的思想,快慢两个指针,通过是否相遇,来判断链表中是否有环。相比于用HashMap的方法,优点是空间复杂度仅为O(1),时间复杂度O(n)。
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while (slow != fast) {
if (fast == null || fast.next == null) {
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}
}