zoukankan      html  css  js  c++  java
  • 【Leetcode】【Medium】Linked List Cycle II

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

    解题:

    寻找单链表中环的入口,如果不存在环则返回null。

    假设单链表有环,先利用判断单链表是否有环(Linked List Cycle)的方法,找到快慢指针的交点。

    假设环的入口在第K个结点处,那么此时快慢指针的交点,距离环入口,还差k个距离。

    快慢指针相交后,在链表头位置同时启动另一个指针target,和慢指针once一样每次只移动一步,那么两者同时移动K步,就会相交于入口处。

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode *detectCycle(ListNode *head) {
    12         if (head == NULL || head->next == NULL) 
    13             return NULL;
    14         ListNode* once = head;
    15         ListNode* twice = head;
    16         ListNode* target = head;
    17         
    18         while (twice->next && twice->next->next) {
    19             once = once->next;
    20             twice = twice->next->next;
    21             if (once == twice) {
    22                 while (target != once) {
    23                     target = target->next;
    24                     once = once->next;
    25                 }
    26                 return target;
    27             }
    28         }
    29         
    30         return NULL;
    31     }
    32 };
  • 相关阅读:
    iOS 内购讲解
    实现抓图的工具2
    实现抓图的工具
    关于胖客户端
    实时进销存
    DataGridView隔行显示不同的颜色
    C#数据库绑定
    VS2012中数据库架构的比较
    delphi使用outputdebugstring调试程序和写系统日志
    drupal7安装中文错误
  • 原文地址:https://www.cnblogs.com/huxiao-tee/p/4591459.html
Copyright © 2011-2022 走看看