题目描述
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
第一想法
- 通过指针地址是否出现重复来判断.
- key value对.
AC代码
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead)
{
ListNode* p = pHead;
map<ListNode* , int> m;
while(p){
if(++m[p] == 2)
return p;
p = p -> next;
}
return p;
}
};
看了讨论区
通过快慢指针的形式
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead)
{
ListNode *fast = pHead, *slow = pHead;
while (fast && fast->next != NULL) {
fast = fast->next->next;
slow = slow->next;
if (fast == slow) {
break;
}
}
if (fast == NULL || fast->next == NULL) {
return NULL;
}
fast = pHead;
while (fast != slow) {
fast = fast->next;
slow = slow->next;
}
return fast;
}
};
网友评论