首页 > 代码库 > leetcode_141_Linked List Cycle

leetcode_141_Linked List Cycle

描述:

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