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

leetcode_141_Linked List Cycle

时间:2015-02-03 13:27:23      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:leetcode   linkedlistcycle   hashset   

描述:

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

思路:

一想到唯一就直接联想到了hashSet,至于在不用额外存储空间的情况下把题目搞出来,这个,确实还没有想到,to be continued......

代码:

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


结果:

技术分享

leetcode_141_Linked List Cycle

标签:leetcode   linkedlistcycle   hashset   

原文地址:http://blog.csdn.net/mnmlist/article/details/43447177

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