判断两个链表是否相交,若相交,求出相交的部分
参考 https://blog.csdn.net/fengxinlinux/article/details/78885764
自己写的代码:
1.根据数组创建单链表;
2.遍历两个单链表,记录长度,若两个链表最后的节点值相等,表示肯定有相交部分;否则,无。
3.若有相交部分,根据长度制定快慢指针,跑出交点位置。
代码:
#include<iostream>
#include<string>
#include<vector>
#include<math.h>
#include<algorithm>
#include<set>
#include<map>
#include<unordered_map>
#include<unordered_set>
#include<queue>
#include<stack>
using namespace std;
const int MOD = 1e9 + 7;
struct ListNode
{
int val;
ListNode* next;
ListNode(int x) :val(x), next(NULL) {}
};
ListNode* structList(vector<int> nums)
{
ListNode* head = new ListNode(-1);
ListNode* p = head;
if (nums.empty())
return p->next;
for (int i = 0; i < nums.size(); ++i)
{
ListNode* node = new ListNode(nums[i]);
p->next = node;
p = node;
}
p->next = NULL;
return head->next;
}
ListNode* interactList(ListNode* list1, ListNode* list2)
{
if (list1 == nullptr || list2 == nullptr)
{
return nullptr;
}
ListNode* p1 = list1, * p2 = list2;
int len1=1, len2=1;
while (p1->next)
{
++len1;
p1 = p1->next;
}
while (p2->next)
{
++len2;
p2 = p2->next;
}
if (p1->val != p2->val)
{
return nullptr;
}
p1 = list1, p2 = list2;
if (len1 > len2)
{
int gap = len1 - len2;
while (gap--)
{
p1 = p1->next;
}
while (p1->val != p2->val)
{
p1 = p1->next;
p2 = p2->next;
}
}
else
{
int gap = len2 - len1;
while (gap--)
{
p2 = p2->next;
}
while (p2->val != p1->val)
{
p1 = p1->next;
p2 = p2->next;
}
}
if (p1->val == p2->val)
return p1;
else
return nullptr;
}
int main()
{
vector<int> nums1 = { 1,4,7};
vector<int> nums2 = { 2,1,3,5,7 };
ListNode* list1 = structList(nums1);
ListNode* list2 = structList(nums2);
ListNode* res = interactList(list1, list2);
ListNode* p = res;
while (p)
{
cout << p->val << " ";
p = p->next;
}
cout << endl;
return 0;
}
