zoukankan      html  css  js  c++  java
  • [leetcode]142. Linked List Cycle II找出循环链表的入口

    Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

    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.

    Note: Do not modify the linked list.

    Example 1:

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

    题意:

    找出循环链表的入口

    思路

    Two Pointers

    脑筋急转弯题。没有深究的价值。

    code

     1 /**
     2  * Definition for singly-linked list.
     3  * class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) {
     7  *         val = x;
     8  *         next = null;
     9  *     }
    10  * }
    11  */
    12 public class Solution {
    13     public ListNode detectCycle(ListNode head) {
    14         ListNode slow = head, fast = head;
    15         while (fast != null && fast.next != null) {
    16             slow = slow.next;
    17             fast = fast.next.next;
    18             if (slow == fast) {
    19                 ListNode slow2 = head;
    20                 while (slow2 != slow) {
    21                     slow2 = slow2.next;
    22                     slow = slow.next;
    23                 }
    24                 return slow;
    25             }
    26         }
    27         return null;
    28     }
    29 }
  • 相关阅读:
    从goauth2的一个bug说起
    Vagrant与skynet框架
    离开博客园了
    (转) Android开发性能优化简介
    ListFragment源码 (待分析)
    Activity来了
    Android下的屏幕适配
    恶心的content
    Android下的xml资源详解
    各个页面样子的实现与演示
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10873403.html
Copyright © 2011-2022 走看看