Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
思路分析:这题很简单,直接用快慢指针法就可以解决,快指针速度是慢指针速度的2倍,如果有环,它们一定会相遇。
AC Code
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null || head.next == null) return false;
//1236
ListNode first = head;
ListNode second = head.next;
while(first != null && second != null && second.next != null){
first = first.next;
second = second.next;
second = second.next;
if(first == second) return true;
}
return false;
}
}