#include <iostream>
#include <vector>
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 *getIntersectionNode(ListNode *headA, ListNode *headB)
{
ListNode *anode = new ListNode();
anode = headA;
ListNode *bnode = new ListNode();
bnode = headB;
while (anode != nullptr)
{
bnode = headB;
while (bnode != nullptr)
{
if (anode == bnode)
{
ListNode *res = new ListNode();
res=anode;
ListNode *temp_anode = new ListNode();
temp_anode = anode->next;
ListNode *temp_bnode = new ListNode();
temp_bnode = bnode->next;
while (temp_anode != nullptr)
{
if (temp_anode == temp_bnode)
{
temp_anode=temp_anode->next;
temp_bnode=temp_bnode->next;
continue;
}
else
break;
}
if (temp_anode == nullptr)
return res;
}
bnode = bnode->next;
}
anode = anode->next;
}
return nullptr;
}
};
int main()
{
// 两条具有交点的链表
vector<int> veca = {4, 1, 8, 4, 5};
ListNode *heada = constructListnode(veca);
vector<int> vecb = {5, 0, 1};
ListNode *headb = constructListnode(vecb);
ListNode *temp_headb = headb;
ListNode *temp_heada = heada;
while (temp_headb->val != 1)
temp_headb = temp_headb->next;
while (temp_heada->val != 8)
temp_heada = temp_heada->next;
temp_headb->next = temp_heada;
// printf链表
printflistnode(heada);
cout << endl;
printflistnode(headb);
cout << endl;
Solution a;
ListNode *res=a.getIntersectionNode(heada, headb);
printflistnode(res);
delete[] heada;
delete[] headb;
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;
}
Leetcode160相交链表(记录)C++
于 2023-06-19 19:31:25 首次发布