首页 > 其他 > 详细

Linked List Cycle II

时间:2015-01-11 14:42:29      阅读:220      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!