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 }
  • 相关阅读:
    用servlet来实现验证码的功能
    Sqlite3 数据库
    xml解析
    Android .9文件
    AsyncTask
    Looper Handler
    URLConnection
    单例模式
    Httpclient访问网络
    json 解析
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6380503.html
Copyright © 2011-2022 走看看