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

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

    此题和之前的find the duplicate number比较像,代码如下:

     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 fast = head;
    15         ListNode slow = head;
    16         while(fast!=null&&fast.next!=null){
    17             fast = fast.next.next;
    18             slow = slow.next;
    19             if(fast==slow){
    20                 fast = head;
    21                 while(fast!=slow){
    22                     fast = fast.next;
    23                     slow = slow.next;
    24                 }
    25                 return fast;
    26             }
    27         }
    28         return null;
    29     }
    30 }
  • 相关阅读:
    $prufer$序列
    倍增
    二分
    英语词汇速查表
    ACM模拟赛
    Trie树
    关于军训的模拟赛-R2
    树上差分
    列队
    斜率优化dp
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6380503.html
Copyright © 2011-2022 走看看