141.Linked List Cycle---双指针

题目连接
ide

题目大意:给出一个链表,判断该链表是否有环,空间复杂度最好控制在o(1)测试

这个题没有给测试用例,致使没太明白题目意思,看了题解,用了两种方法示例以下:spa

法一(借鉴):利用两个指针,一个指针步长为2,一个指针步长为1,若链表中有环,则两个指针同时走,在某一时刻必定会走到一块儿;若链表中没有环,则两个指针必定会走到null,代码以下(耗时1ms):指针

 1     public boolean hasCycle(ListNode head) {
 2         ListNode fast = head;
 3         ListNode slow = head;
 4         while(fast != null && slow != null && fast.next != null) {
 5             slow = slow.next;
 6             fast = fast.next.next;
 7             if(slow == fast) {
 8                 return true;
 9             }
10         }
11         return false;
View Code

法二(借鉴):利用set集合中的contains,判断是否有两个相同的结点在集合中,若是有,则有环,代码以下(耗时10ms):code

 1         Set<ListNode> list = new HashSet<>();
 2         while(head != null) {
 3             if(list.contains(head)) {
 4                 return true;
 5             }
 6             else {
 7                 list.add(head);
 8                 head = head.next;
 9             }
10         }
11         return false;    
View Code
相关文章
相关标签/搜索