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?

首先指出:这个程序可以解决Linked List Cycle I的问题,同时之前Linked List Cycle I 的解法虽然可以AC但是破坏了链表结构,不是很合适

解题思路:让2个指针向前跑,一个一次跑一格,一个一次跑两格,如果有环,迟早相遇,在用一个指针从某个位置跑,通过关系式找到入口。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
      if(head==NULL || head->next == NULL)return NULL;
      
      ListNode *slow=head,*fast=head,*entry=head;
      
      while(fast->next && fast->next->next)
      {
          slow = slow->next;
          fast = fast->next->next;
          if(slow == fast)
          {
              while(slow != entry)
              {
                  slow = slow->next;
                  entry = entry->next;
                  
              }
              return entry;
          }
      }
      return NULL;
    }
};

 

posted @ 2014-12-12 00:57  ElephantKing  阅读(97)  评论(0编辑  收藏  举报