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 }
  • 相关阅读:
    蜕变过程中的思考
    Django template for 循环用法
    Django 发送html邮件
    Django F对象的使用
    在Django中使用Q()对象
    ubuntu中管理用户和用户组
    Django settings.py 的media路径设置
    Git版本控制 备忘录
    Git .gitignore文件的使用
    将git关联到pycharm
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10873403.html
Copyright © 2011-2022 走看看