题解 | #链表中环的入口结点#
链表中环的入口结点
http://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4
链表中的环
第一种:快慢指针解决环问题
快指针一次移动两次,慢指针一次移动一次,判断条件为快慢指针相遇,如果快指针为空(表示没环)如果相遇则有环,则快指针指向初试,然后快慢指针每次移动一次,直到相遇即环入口。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead) {
if(pHead == NULL || pHead->next == NULL)return NULL;
ListNode *fast = pHead->next->next, *slow = pHead->next;
while(fast != slow){
slow = slow->next;
if(fast == NULL || fast->next == NULL)return NULL;
fast = fast->next->next;
}
fast = pHead;
while(fast != slow){
fast = fast->next;
slow = slow->next;
}
return fast;
}
};
方法二:hashset保存,如果有重复即环入口
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead) {
unordered_set<ListNode*> s;
while(pHead){
if(s.count(pHead))return pHead;
s.insert(pHead);
pHead = pHead->next;
}
return NULL;
}
};