• 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;
        }
    }




  • 相关阅读:
    NOIP2011 D1T1 铺地毯
    NOIP2013 D1T3 货车运输 倍增LCA OR 并查集按秩合并
    POJ 2513 trie树+并查集判断无向图的欧拉路
    599. Minimum Index Sum of Two Lists
    594. Longest Harmonious Subsequence
    575. Distribute Candies
    554. Brick Wall
    535. Encode and Decode TinyURL(rand and srand)
    525. Contiguous Array
    500. Keyboard Row
  • 原文地址:https://www.cnblogs.com/zhxshseu/p/246071fa65cc74ff69bfe018c8189447.html
Copyright © 2020-2023  润新知