首页 > 其他 > 详细

leetcode_142_Linked List Cycle II

时间:2015-02-04 20:24:35      阅读:245      评论: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?

思路:

从头开始遍历链表并将结点的引用存储在HashSet中,出现重复的地方就是出现环的地方。

代码:

public ListNode detectCycle(ListNode head) {
		if(head==null)
			return null;
        HashSet<ListNode>set=new HashSet<ListNode>();
        ListNode pListNode=head;
        while(pListNode!=null)
        {
        	if(set.contains(pListNode))
        		return pListNode;
        	else
        	{
        		set.add(pListNode);
        		pListNode=pListNode.next;
        	}
        		
        }
		return  null;
    }

结果:

技术分享

leetcode_142_Linked List Cycle II

原文:http://blog.csdn.net/mnmlist/article/details/43491711

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!