首页 > 其他 > 详细

[LintCode] Linked List Cycle

时间:2017-10-13 13:28:18      阅读:160      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/lz87/p/7205126.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!