• 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 }
  • 相关阅读:
    JavaScript基础语法及字符串相关方法(1)
    matplotlib实现三维柱状图
    前端入门CSS(3)
    博客页面练习
    前端入门CSS(2)
    前端入门CSS(1)
    前端入门html(表单)
    Longest Palindromic Substring
    Wildcard Matching
    Spiral Matrix II
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/3798589.html
Copyright © 2020-2023  润新知