leetcode_141_Linked List Cycle

来源:互联网 发布:网络安全法宣传图片 编辑:程序博客网 时间:2024/05/22 12:52

描述:

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;    }


结果:


0 0
原创粉丝点击