题解 | #判断链表中是否有环#
判断链表中是否有环
https://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
import java.util.*; /** * 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) { return false; } // 双指针法,如果有循环,则必会相交 ListNode targetNode = head; return hasCycle(head, targetNode); } public boolean hasCycle(ListNode head, ListNode targetNode) { if (targetNode.next == null || targetNode.next.next == null) { return false; } if (targetNode.next.next == head.next) { return true; } return hasCycle(head.next, targetNode.next.next); } }
要求空间复杂度为O(1),可以使用双指针法,(slow指针每次移动一个位置,fast指针每次移动两个位置)如果存在闭环,那么最终必会相交。如果不存在闭环,那么最近获取next时会得到null值。
#闭环#