zoukankan      html  css  js  c++  java
  • 0141. Linked List Cycle (E)

    Linked List Cycle (E)

    题目

    Given a linked list, determine if it has a cycle in it.

    To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

    Example 1:

    Input: head = [3,2,0,-4], pos = 1
    Output: true
    Explanation: There is a cycle in the linked list, where tail connects to the second node.
    

    Example 2:

    Input: head = [1,2], pos = 0
    Output: true
    Explanation: There is a cycle in the linked list, where tail connects to the first node.
    

    Example 3:

    Input: head = [1], pos = -1
    Output: false
    Explanation: There is no cycle in the linked list.
    

    Follow up:

    Can you solve it using O(1) (i.e. constant) memory?


    题意

    判断给定链表中是否存在环。

    思路

    比较简单的就是将所有遍历到的结点记录下来,如果记录了两次则说明存在环。

    (O(1))空间的方法是使用快慢指针,慢指针每次走一步,快指针每次走两步,如果快指针追上慢指针则说明存在环。实际上可以看做一个相遇问题,如果快慢指针都在一个环中,且快指针距离慢指针还有n个结点的距离,那么经过n个回合后快指针必定与慢指针重合。


    代码实现

    Java

    Hash

    public class Solution {
        public boolean hasCycle(ListNode head) {
            if (head == null) {
                return false;
            }
    
            Set<ListNode> set = new HashSet<>();
            while (head != null) {
                if (!set.add(head)) {
                    return true;
                }
                head = head.next;
            }
            
            return false;
        }
    }
    

    快慢指针

    public class Solution {
        public boolean hasCycle(ListNode head) {
            if (head == null) {
                return false;
            }
    
            ListNode slow = head, fast = head;
            while (fast.next != null && fast.next.next != null) {
                slow = slow.next;
                fast = fast.next.next;
                if (fast == slow) {
                    return true;
                }
            }
    
            return false;
        }
    }
    

    JavaScript

    /**
     * @param {ListNode} head
     * @return {boolean}
     */
    var hasCycle = function (head) {
      const nodes = new Set()
      while (head) {
        if (nodes.has(head)) {
          return true
        }
        nodes.add(head)
        head = head.next
      }
      return false
    }
    
  • 相关阅读:
    IPFS实践之初体验
    自己写的屏幕录像及播放软件
    绿色ip扫描工具
    ASIHTTPRequest 编码问题
    ios开发中,A valid provisioning profile for this executable was not found,的解决方法
    毕业设计之蚁群算法的研究——起始篇
    分享两个模拟get和post方法的工具类,让应用能够与服务器进行数据交互
    安卓中生成二维码和扫描二维码
    分享一个安卓中异步获取网络图片并自适应大小的第三方程序(来自github)
    不只是个程序员
  • 原文地址:https://www.cnblogs.com/mapoos/p/14368984.html
Copyright © 2011-2022 走看看