码迷,mamicode.com
首页 > 其他好文 > 详细

Linked List Cycle II

时间:2015-01-11 14:44:45      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

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 }

 

Linked List Cycle II

标签:

原文地址:http://www.cnblogs.com/luckygxf/p/4216415.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!