
Linked List, Easy
Question
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Answer
HashSet
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
* Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class { public boolean hasCycle(ListNode head) { HashSet<ListNode> hashset = new HashSet<>(); while(head!=null){ if(hashset.contains(head)) return true; else{ hashset.add(head); head = head.next; } } return false; } }
|
Running time: O(n)
Fast and Slow pointer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
* Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class { public boolean hasCycle(ListNode head) { ListNode fast = head; ListNode slow = head; while(fast!=null&&fast.next!=null){ fast = fast.next.next; slow = slow.next; if(fast == slow) return true; } return false; } }
|
Running time: O(n)
近期评论