LC_141. Linked List Cycle

Posted davidnyc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LC_141. Linked List Cycle相关的知识,希望对你有一定的参考价值。

https://leetcode.com/problems/linked-list-cycle/description/

 

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

time: o(n) space: o(1)

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

if you use extra space, then it means using hashMap<val, listNode>   time: o(n) space: o(n)

以上是关于LC_141. Linked List Cycle的主要内容,如果未能解决你的问题,请参考以下文章

141. Linked List Cycle

LeetCode141 Linked List Cycle. LeetCode142 Linked List Cycle II

141. Linked List Cycle

141. Linked List Cycle

141. Linked List Cycle

141. Linked List Cycle