题目:
如果一个链表中包含环,设计一个函数找出环的入口节点。
解题思路:
- 快慢指针 -> 定位环内节点
- 定义辅助节点得到环的长度k
- 节点1从头先走k次,节点2出发,相遇点即为环的入口点
代码:
#include "pch.h"
#include<iostream>
using namespace std;
struct ListNode {
int value;
ListNode* next;
};
ListNode* RingNode(ListNode* Node) {
if (Node == nullptr) return nullptr;
ListNode* pSlow = Node;
ListNode* pFast = Node;
while (!(pFast->next == nullptr || pFast->next->next == nullptr)) {
pSlow = pSlow->next;
pFast = pFast->next->next;
if (pSlow == pFast)return pSlow;
}
return nullptr;
}
int RingLen(ListNode* Node) {
if (Node == nullptr)return 0;
int len = 1;
ListNode* tmp = Node->next;
while (tmp != Node) {
len++;
tmp = tmp->next;
}
return len;
}
ListNode* findEntance(ListNode* node, int len) {
if (len == 0 || node == nullptr )return nullptr;
ListNode* preNode = node;
for (int i = 0; i < len; i++) {
preNode = preNode->next;
}
ListNode* res = node;
while (res != preNode) {
res = res->next;
preNode = preNode->next;
}
return res;
}
int main()
{
ListNode* p1 = new ListNode();
p1->value = 4;
ListNode* p2 = new ListNode();
p2->value = 3;
p2->next = p1;
ListNode* p3 = new ListNode();
p3->value = 2;
p3->next = p2;
ListNode* p4 = new ListNode();
p4->value = 1;
p4->next = p3;
p1->next = p3;
ListNode* ringNode = RingNode(p4);
int len = RingLen(ringNode);
ListNode* entrance = findEntance(p4, len);
//cout << entrance->value;
}
注意代码的防御性!