判断两个单链表是否有交叉

思路:只需两层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;
}

相关文章

这篇文章主要介绍“基于nodejs的ssh2怎么实现自动化部署”的...
本文小编为大家详细介绍“nodejs怎么实现目录不存在自动创建...
这篇“如何把nodejs数据传到前端”文章的知识点大部分人都不...
本文小编为大家详细介绍“nodejs如何实现定时删除文件”,内...
这篇文章主要讲解了“nodejs安装模块卡住不动怎么解决”,文...
今天小编给大家分享一下如何检测nodejs有没有安装成功的相关...