给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null
。
这道题解法很巧妙,是个追击问题,首先是确定是否有环。然后在根据追击相遇点与表头的关系来寻找入环点。
python:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None:
return None
if head.next == None:
return None
slow = head
fast = head
while(fast):
slow = slow.next
if fast.next:
fast = fast.next.next
if fast == slow:
break
else:
return None
if fast == None :
return None
slow = head
while(slow != fast):
slow = slow.next
fast = fast.next
return slow
C++:
/**
* 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) return NULL;
if(!(head->next)) return NULL;
ListNode* slow = head;
ListNode* fast = head;
while(fast){
slow = slow->next;
if(fast->next){
fast = fast->next->next;
if(fast == slow) break;
}
else{
return NULL;
}
}
if(!fast) return NULL;
slow = head;
while(slow != fast){
slow = slow->next;
fast = fast->next;
}
return slow;
}
};