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?
Algorithm
Thought 1:
Fast and slow pointers. When two pointers meet each other, it indicates that there is a ring. Otherwise, there is no ring. It may need to be traversed multiple times. The space complexity is O (1), and the time complexity is O (n)
1 public class Solution { 2 public boolean hasCycle(ListNode head) { 3 if(head == null) return false; 4 ListNode fast = head; 5 ListNode slow = head; 6 while(true){ 7 if(fast.next == null || fast.next.next == null) return false; 8 fast = fast.next.next; 9 slow = slow.next;10 if(fast == slow) return true;11 }12 }13 }
Idea 2:
Hash table. When a node has two prefixes, the node is the starting point of the ring and only needs to be traversed once. The space complexity is O (n), and the time complexity is O (n)
1 public class Solution { 2 public boolean hasCycle(ListNode head) { 3 if(head == null) return false; 4 ListNode tem = new ListNode(0); 5 tem.next = head; 6 Map<ListNode,ListNode> hash = new HashMap<ListNode,ListNode>(); 7 while(true){ 8 if(tem.next == null) return false; 9 if(hash.get(tem.next) != null) return true;10 hash.put(tem.next,tem);11 tem = tem.next;12 }13 }14 }
Idea 2 is the solution of linked list cycle II.
The listnode structure is as follows:
1 public class ListNode {2 int val;3 ListNode next;4 ListNode(int x){5 val = x;6 next = null;7 }8 }View code