[LintCode] Linked List Cycle
Posted Push your limit!
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LintCode] Linked List Cycle相关的知识,希望对你有一定的参考价值。
Given a linked list, determine if it has a cycle in it.
Example
Given -21->10->4->5, tail connects to node index 1, return true
Challenge
Follow up:
Can you solve it without using extra space?
Solution 1. O(n) runtime, O(n) space with HashSet
1 /** 2 * Definition for ListNode. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int val) { 7 * this.val = val; 8 * this.next = null; 9 * } 10 * } 11 */ 12 13 14 public class Solution { 15 /* 16 * @param head: The first node of linked list. 17 * @return: True if it has a cycle, or false 18 */ 19 public boolean hasCycle(ListNode head) { 20 HashSet<ListNode> visited = new HashSet<ListNode>(); 21 ListNode curr = head; 22 while(curr != null) { 23 if(!visited.add(curr)) { 24 return true; 25 } 26 curr = curr.next; 27 } 28 return false; 29 } 30 }
Solution 2. O(n) runtime, O(1) space, two pointers
1 public class Solution { 2 public boolean hasCycle(ListNode head) { 3 if(head == null) { 4 return false; 5 } 6 ListNode slow = head, fast = head.next; 7 while(fast != null && fast.next != null) { 8 fast = fast.next; 9 if(slow == fast) { 10 return true; 11 } 12 else { 13 slow = slow.next; 14 fast = fast.next; 15 } 16 } 17 return false; 18 } 19 }
Related Problems
Intersection of Two Linked Lists
以上是关于[LintCode] Linked List Cycle的主要内容,如果未能解决你的问题,请参考以下文章
lintcode-medium-Reverse Linked List II
lintcode-easy-Flatten Binary Tree to Linked List
lintcode-easy-Remove Linked List Elements