142. 环形链表 II
题目描述
给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
思路
- 方法一:哈希表
直接把节点指针记录在哈希表里,每次查表,有重复就是环。
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
unordered_set<ListNode *> visited;
while (head != nullptr) {
if (visited.count(head)) {
return head;
}
visited.insert(head);
head = head->next;
}
return nullptr;
}
};
- 方法二:快慢指针
首先,有一对快慢指针,从头节点出发,慢指针走1步,快指针走2步,当快指针追上慢指针的时候,就意味着有环。
慢指针重新回到头节点,快指针慢指针都每次向前1步,再次相遇的位置就是链表开始入环的第一个节点。
```cpp
/**
* 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 *slow = head;
ListNode *fast = head;
while(slow != NULL && fast != NULL && fast -> next != NULL){
slow = slow -> next;
fast = fast -> next -> next;
if(slow == fast){
ListNode *slow = head;
while(slow != NULL && fast != NULL){
if(slow == fast){
return slow;
}
slow = slow -> next;
fast = fast -> next;
}
}
}
return NULL;
}
};