Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Subscribe to see which companies asked this question.
思路:用两个遍历指针,一个每次前进一步,一个每次前进两步,如果有环,则这两个指针会相遇。
/** * 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) { ListNode p, q; if (head == null || head.next == null) { return false; } p = q = head; while (true) { if (q == null ||q.next == null || p == null) { return false; } p = p.next; q = q.next.next; if (q == p) { break; } } return true; } }