剑指offer056:链表中环的入口结点
题目描述
题目描述
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
解法一:基于快慢指针的方法
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead)
{
ListNode* fast = pHead, *low = pHead;
while (fast&&fast->next)
{
fast = fast->next->next;
low = low->next;
if (fast == low)
break;
}
if (!fast || !fast->next)
return NULL;
low = pHead;
while (fast != low)
{
fast = fast->next;
low = low->next;
}
return low;
}
};
解法二:基于set的方法
class Solution2 {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead)
{
set<ListNode*> s;
ListNode* node = pHead;
while (node != NULL) {
if (s.insert(node).second)
node = node->next;
else
return node;
}
return node;
}
};
main函数
#include "stdafx.h"
#include <iostream>
using namespace std;
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
int main()
{
system("pause");
return 0;
}