思路:只需两层while循环即可,事件复杂度O(n*m),外层循环代表其中体格链表指针每次只移动一个位置,内层循环代表另一个链表的指针需从头到尾移动每次移动一个位置,每次都需要判断当前指针是不是等于外层循环的指针,如果相等,则代表有交叉。当两层循环结束后,还没碰到相同的情况,则代表无交叉。
点击查看代码
#include <iostream>
using namespace std;
struct Node {
Node* next;
//int value;
};
bool has_overlap(Node* head_one, Node* head_two)
{
if (head_one->next == NULL || head_two->next == NULL)
return false;
Node* p_one = head_one;
Node* p_two = head_two;
while (p_one->next != NULL)
{
p_two = head_two;
while (p_two->next != NULL)
{
if (p_one == p_two)
return true;
p_two = p_two->next;
}
p_one = p_one->next;
}
return false;
}
int main()
{
Node* head = new Node;
head->next = NULL;
Node* p1 = new Node;
head->next = p1;
Node* p2 = new Node;
p1->next = p2;
p2->next = NULL;
Node* head1 = new Node;
head1->next = NULL;
Node* p11 = new Node;
head1->next = p11;
Node* p21 = new Node;
p11->next = p21;
p21->next = NULL;
if (has_overlap(head, head1))
{
cout << "有交叉" << endl;
}
else
{
cout << "无交叉" << endl;
}
p21->next = p1;
if (has_overlap(head, head1))
{
cout << "有交叉" << endl;
}
else
{
cout << "无交叉" << endl;
}
return 0;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。