链表节点:
struct ListNode
{
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
返回环路起始节点(即被两个节点所指的节点)类设计,如图:
遍历链表,计算节点与表头地址的距离,将距离值存储于vector<long long> dis数组,因为链表存在回路,当所有节点遍历完成后会回到环路起始节点,如上图中的2号点,此时计算出的与表头之间的距离值在dis数组早已存在,以此便能判断节点是否为环路起始节点。
类代码:
class Solution
{
public:
ListNode *detectCycle(ListNode *head)
{
if (head == nullptr || head->next == nullptr)
return nullptr;
if(head->next->next==head)
return head;
vector<long long> dis;
ListNode *anode = head->next;
while(anode!=nullptr)
{
long long adis=anode-head;
if(find(begin(dis),end(dis),adis)!=end(dis))
return anode;
dis.push_back(adis);
anode=anode->next;
}
return nullptr;
}
};
上述采用vector来存储距离值,但数组在查找时效率较低,可采用哈希表的方法提升效率,如下:
class Solution
{
public:
ListNode *detectCycle(ListNode *head)
{
if (head == nullptr || head->next == nullptr)
return nullptr;
if(head->next->next==head)
return head;
unordered_set<int> dis;
ListNode *anode = head->next;
while(anode!=nullptr)
{
long long adis=anode-head;
if(dis.count(adis))
return anode;
dis.insert(adis);
anode=anode->next;
}
return nullptr;
}
};
完整代码如下:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <unordered_set>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
int printflistnode(ListNode *head);
template <class T>
ListNode *constructListnode(vector<T> vec);
class Solution
{
public:
ListNode *detectCycle(ListNode *head)
{
if (head == nullptr || head->next == nullptr)
return nullptr;
if(head->next->next==head)
return head;
unordered_set<int> dis;
ListNode *anode = head->next;
while(anode!=nullptr)
{
long long adis=anode-head;
if(dis.count(adis))
return anode;
dis.insert(adis);
anode=anode->next;
}
return nullptr;
}
};
int main()
{
// 生成环
vector<int> veca = {1,7,7,4,19,6,-9,5,2,5};
ListNode *head = constructListnode(veca);
ListNode *ahead = head;
ListNode *temp_head = head;
while (temp_head->val != -9)
temp_head = temp_head->next;
while (ahead->next != nullptr)
ahead = ahead->next;
ahead->next = temp_head;
Solution a;
ListNode *res = a.detectCycle(head);
cout<<res->val;
delete[] head;
return 0;
}
int printflistnode(ListNode *head)
{
ListNode *next_node = head;
while (next_node != nullptr)
{
cout << next_node->val;
next_node = next_node->next;
}
return 0;
}
template <class T>
ListNode *constructListnode(vector<T> vec)
{
ListNode *head = nullptr;
if (vec.size() > 0)
{
head = new ListNode(vec[0]);
ListNode *last_node = new ListNode();
for (int i = 1; i < vec.size(); i++)
{
if (i == 1)
{
head->next = new ListNode(vec[i]);
last_node = head->next;
}
else
{
last_node->next = new ListNode(vec[i]);
last_node = last_node->next;
}
}
}
return head;
}