首页 > 代码库 > leetcode-142. Linked List Cycle II

leetcode-142. Linked List Cycle II

 

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

Note: Do not modify the linked list.

Follow up:
Can you solve it without using extra space?

 

思路:不同于141. Linked List Cycle 这题的head节点可能没在环里,而且不光判断是否有环,还要返回环的起点,所以不能再用快慢指针了,改用修改节点数据值,修改为一个不常用的数,我修改为INT_MAX。如果遇到值为INT_MAX的节点,就说明有环,并且为环的起点(虽然这种方法在逻辑上不完美,但是这题Accepted了,如果有更好的方法,欢迎指教)

 

Accepted Code:

 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==nullptr)
13         return nullptr;
14         
15         ListNode* flag=nullptr;
16         while(head)
17         {
18             head->val=INT_MAX;
19             head=head->next;
20             if(head==nullptr)
21             return nullptr;
22             if(head->val==INT_MAX)
23             {
24                 flag=head;
25                 break;
26             }
27         }
28         return flag;
29     }
30 };

 

leetcode-142. Linked List Cycle II