142. 环形链表 II
https://leetcode-cn.com/problems/linked-list-cycle-ii/description/
给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
说明:不允许修改给定的链表。
进阶:
你是否可以不用额外空间解决此题?
/**
* 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* cur1 = head;
ListNode* cur2 = head;
ListNode* meetNode = NULL;
while(cur1 && cur1->next){
cur1 = cur1->next->next;
cur2 = cur2->next;
if(cur1 == cur2){
break;
}
}
if(cur1 != cur2){
return NULL;
}
meetNode = cur1;
cur1 = head;
while(cur1 != meetNode){
cur1 = cur1->next;
meetNode = meetNode->next;
}
return meetNode;
}
};