题目描述
Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.
Follow up:
Can you solve it without using extra space?
解题思路:
建立一个HashSet, 每访问一个节点就判断HashSet中是否已经存在,如果有,则直接返回;如果没有,则返回空
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ import java.util.*; public class Solution { public ListNode detectCycle(ListNode head) { Set<ListNode> sets = new HashSet<ListNode>(); ListNode tmp = head; while (tmp != null) { if (!sets.contains(tmp)) { sets.add(tmp); tmp = tmp.next; } else { break; } } return tmp; } }