Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
设两个指针,一个走两步,一个走一步,如果有环,快的一定会和慢的汇合
Source
/**
* 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;
ListNode p = head, q = head;
while(q.next != null && q.next.next != null){ //由于此题不是找中间位置,所以可以写为判断本身和next的值是否为null,不影响
p = p.next;
q = q.next.next;
if(p == q) return true;
}
return false;
}
}