Linked List Cycle II

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?

题意

判断一个链表是否有环,如果没有环,返回null。如果有环返回环开始的节点

思路

这里我用的是hash表来做,遍历链表,如果链表没有出现在hash表中,put到hash表中,如果在hash表中出现过,说明出现环,返回节点。遍历到链表最后,说明没有环,返回空

 1 import java.util.Hashtable;
 2 public class Solution {    
 3     public ListNode detectCycle(ListNode head) {        
 4         Hashtable<ListNode, ListNode> hashtable = new Hashtable<ListNode, ListNode>();
 5         while(head != null){
 6             ListNode temp = hashtable.get(head);
 7             if(temp == null){
 8                 hashtable.put(head, head);
 9                 head = head.next;
10                 continue;
11             }
12             else{
13                 return temp;
14             }//else
15         }//else
16         
17         return null;
18     }
19 }

 

posted on 2015-01-11 13:35  luckygxf  阅读(167)  评论(0编辑  收藏  举报

导航