LeetCode(141) 判断链表中是否有环

137 阅读1分钟

Given a linked list, determine if it has a cycle in it.

给定一个链表,判断链表中是否有环。

关键技巧:快慢指针,如果有环的话,快指针一定会追上慢指针。

/**
 * 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 quick = head;
        ListNode slow = head;
        while (quick.next != null && quick.next.next != null){
            quick = quick.next.next;
            slow = slow.next;
            if (quick == slow){
                return true;
            }
        }
        return false;
    }
}