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?
思路:先求出环的相遇点,然后再此处分开会成为不规则的Y形,求出两条链的长度,然后作差,让长的链先移动差的距离,
再同时移动找出交点。
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *front = NULL, *rear = NULL;
if(NULL == head) return NULL;
front = head;
rear = head->next;
while(front != rear && NULL != rear){
front = front->next;
rear = rear->next;
if(rear){
rear = rear->next;
}
}
if(NULL == rear) return NULL;
ListNode *newHead = rear;
ListNode *ptr = head, *ptr1 = NULL;
int cnt = 0;
int list1 = 0, list2 = 0;
while(ptr != newHead){
ptr = ptr->next;
list1++;
}
ptr = newHead->next;
while(ptr != newHead){
ptr = ptr->next;
list2++;
}
list2++;
ptr = head; ptr1 = newHead;
if(list2 > list1){
ptr1 = newHead;
while(cnt < list2 - list1){
ptr1 = ptr1->next;
cnt++;
}
}else{
ptr = head; cnt = 0;
while(cnt < list1 - list2){
ptr = ptr->next;
cnt++;
}
}
while(ptr != ptr1){
ptr = ptr->next;
ptr1 = ptr1->next;
}
return ptr;
}
};