其他分享
首页 > 其他分享> > 判断两个单链表是否有交叉

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

作者:互联网

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

标签:Node,head,单链,交叉,two,next,判断,new,NULL
来源: https://www.cnblogs.com/arivin/p/16247662.html