zoukankan      html  css  js  c++  java
  • [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

  • 相关阅读:
    C# String.Format格式说明
    jQuery.json.js
    禁止别人使用"另存为"保存你的网页
    组合问题的递归算法
    jQuery,contents()
    C#string,StringBuilder和Regex类的讲解
    jQuery性能优化指南
    加密算法的C#实现
    m,n组合算法
    jQuery插件—获取URL参数
  • 原文地址:https://www.cnblogs.com/lz87/p/7205126.html
Copyright © 2011-2022 走看看