• [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?

    解题方案:

    假设循环节点距离头节点距离为L,那么当快指针和慢指针第一次相遇时,快指针和慢指针走的距离分别是K1, K2,则:

    K1 = 2K2, K1 - K2 = (S - L)的整数倍,那么K2 = S - L。

    下面让慢指针回到头节点,快指针不动,则快慢指针距离循环结点的距离都是L,所以当快慢节点每次都增加1的时候,相遇点就是循环点。下面是该题代码:

     1 class Solution {
     2 public:
     3     ListNode *detectCycle(ListNode *head) {
     4         int IsCircle = 0;
     5         struct ListNode *slow = head;
     6         struct ListNode *fast = head;
     7 
     8         while (fast != NULL && fast->next != NULL) {
     9             slow = slow->next;
    10             fast = fast->next->next;
    11 
    12             if (slow == fast) {
    13                 IsCircle = 1;
    14                 break;
    15             }
    16         }
    17 
    18         if (IsCircle == 0) {
    19             return NULL;
    20         }
    21 
    22         slow = head;
    23         while(fast != slow) {
    24             fast = fast->next;
    25             slow = slow->next;
    26         }
    27 
    28         return fast;
    29     }
    30 };
  • 相关阅读:
    FTP文件传输应用分析
    A*寻路算法
    Asp.net页面事件引发后台程序处理原理
    开发人员的基本原则(转)
    定位new表达式
    常量对象的动态分配和释放
    PostThreadMessage使用
    最美丽的数学公式
    仿函数
    CF1598EStaircases【计数】
  • 原文地址:https://www.cnblogs.com/skycore/p/4025572.html
Copyright © 2020-2023  润新知