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

    Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
    
    Follow up:
    Can you solve it without using extra space?

    一次过,还是Runner Technique的方法

     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         if (head == null || head.next == null) return null;
    15         ListNode runner = head;
    16         ListNode walker = head;
    17         while (runner != null && runner.next != null) {
    18             runner = runner.next.next;
    19             walker = walker.next;
    20             if (runner == walker) break;
    21         }
    22         if (runner != walker) return null;
    23         runner = head;
    24         while (runner != walker) {
    25             runner = runner.next;
    26             walker = walker.next;
    27         }
    28         return walker;
    29     }
    30 }
  • 相关阅读:
    php 解析xml
    php
    php 设置自动加载某个页面
    Mac
    mysql
    Git
    C#
    C# 正则表达式
    C# ASCII码排序
    (转)datagridview 自定义列三步走
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/3798589.html
Copyright © 2011-2022 走看看