LeetCode 题解之Linked List Cycle II

1、题目描述

 

2、问题分析

使用快慢指针方法判断链表是否有环,然后寻找环开始的节点。

 

3、代码

 1 ListNode *detectCycle(ListNode *head) {
 2         if( head == NULL || head->next == NULL ){
 3             return NULL ;
 4         }
 5         
 6         ListNode* fast = head;
 7         ListNode* slow = head;
 8         
 9         while( fast != NULL && slow != NULL ){
10             
11             if( fast->next !=  NULL ){
12                 fast = fast->next->next;
13             }else{
14                 return NULL ;
15             }
16             slow = slow->next;
17             if( fast == slow ){
18                 break;
19             }
20         }
21         
22         if( fast == NULL || slow == NULL ){
23             return NULL;
24         }
25         
26         ListNode* start = head;
27         while( start != slow ){
28             start = start->next ;
29             slow = slow->next;
30         }
31         
32         return start;
33         
34         
35     }

 

posted @ 2018-07-13 16:17  山里的小勇子  阅读(118)  评论(0编辑  收藏  举报