Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Follow up:
Can you solve it without using extra space?
從頭開始遍歷鏈表並將結點的引用存儲在HashSet中,出現重復的地方就是出現環的地方。
public ListNode detectCycle(ListNode head) { if(head==null) return null; HashSetset=new HashSet (); ListNode pListNode=head; while(pListNode!=null) { if(set.contains(pListNode)) return pListNode; else { set.add(pListNode); pListNode=pListNode.next; } } return null; }