zoukankan      html  css  js  c++  java
  • Linked List Cycle II

    Given a linked list, return the node where the cycle begins.

    If there is no cycle, return null.

    Example

    Given -21->10->4->5, tail connects to node index 1,return 10

    分析

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    /**
     * Definition for ListNode.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int val) {
     *         this.val = val;
     *         this.next = null;
     *     }
     * }
     */ 
    public class Solution {
        /**
         * @param head: The first node of linked list.
         * @return: The node where the cycle begins. 
         *           if there is no cycle, return null
         */
        public ListNode detectCycle(ListNode head) {  
            // write your code here
            ListNode slow = head, fast = head;
            ListNode Pos = null;
            while(fast != null && fast.next != null && fast.next.next != null){
                slow = slow.next;
                fast = fast.next.next;
                if(fast == slow){
                    Pos = slow;
                    break;
                }
            }
            if(Pos == nullreturn null;
             
            while(head != Pos){
                head = head.next;
                Pos = Pos.next;
            }
            return Pos;
        }
    }




  • 相关阅读:
    Mac下各种编程环境的配置问题(python java)
    hackintosh和windows时区问题
    CAN波特率计算公式
    Jetson nano 安装 TensorFlow
    python逻辑运算符优先级
    CSS知识点(一)
    HTML标签(二)
    python2与python3的区别
    HTML标签(一)
    IO多路复用和协程
  • 原文地址:https://www.cnblogs.com/zhxshseu/p/246071fa65cc74ff69bfe018c8189447.html
Copyright © 2011-2022 走看看