/*判断链表是否有回环。 * 1.哈希表:利用HashSet的contains方法来判断是否已经存在该ListNode元素,或者利用HashSet的去重复机制,来判断是否存在该元素,从而判断是否有回环。 * 2.双指针:定义一快一慢指针,若链表存在回环,则两指针必须会相遇。 * 判断的初始条件为slow == fast 结束循环,故初始化时fast不能和slow同为开始节点。 * * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } * */ import java.util.HashSet; import java.util.Set; public class HasCrycle { public boolean hasCycle(ListNode head) { Set<ListNode> set = new HashSet<>(); ListNode res = new ListNode(); res = head; while(res!= null){ if(set.contains(res)){ return true; } set.add(res); res = res.next; } return false; } public boolean hasCycle1(ListNode head) { if(head == null || head.next == null){ return false; } ListNode slow = head; ListNode fast = head.next; while(slow != fast){ if(fast == null || fast.next == null){ return false; } slow = slow.next; fast = fast.next.next; } return true; } }
leetcode---链表回环问题
最新推荐文章于 2022-12-30 15:46:35 发布