判断两单链表是否相交

#include <stdio.h>

struct Node
{
    int data;
    struct Node * next;
};


struct Node * FindLoopPort(struct Node * head)
{
    struct Node * slow = head, *fast = head;

    while(fast && fast->next )
    {
        slow = slow->next;
        fast = fast->next->next;
        if ( slow == fast ) break;
    }

    if (fast == NULL || fast->next == NULL)
        return NULL;

    slow = head;
    while(slow != fast)
    {
         slow = slow->next;
         fast = fast->next;
    }

    return slow;
}

struct Node * FindTail(struct Node * head)
{
    while(head)
    {
        if(!head->next)
            break;

        head = head->next;
    }

    return head;
}

bool IsIntersect(struct Node * head1, struct Node * head2)
{
    struct Node * port1 = FindLoopPort(head1);
    struct Node * port2 = FindLoopPort(head2);
    if(port1 == NULL && port2 == NULL)
    {
        struct Node * tail1 = FindTail(head1);
        struct Node * tail2 = FindTail(head2);
        if(tail1 == tail2)
        {
            return true;
        }
    }
    else if(port1 != NULL && port2 != NULL)
    {
        struct Node * port3 = port1;
        do
        {
            if(port1 == port2)
            {
                return true;
            }

            port1 = port1->next;
        }while(port1 != port3);
    }

    return false;
}

int main()
{
    struct Node * node1 = new Node(); node1->data = 1; node1->next = NULL;
    struct Node * node2 = new Node(); node2->data = 2; node2->next = NULL;
    struct Node * node3 = new Node(); node3->data = 3; node3->next = NULL;
    struct Node * node4 = new Node(); node4->data = 4; node4->next = NULL;
    struct Node * node5 = new Node(); node5->data = 5; node5->next = NULL;
    struct Node * node6 = new Node(); node6->data = 6; node6->next = NULL;
    struct Node * node7 = new Node(); node7->data = 7; node7->next = NULL;
    struct Node * node8 = new Node(); node8->data = 8; node8->next = NULL;
    struct Node * node9 = new Node(); node9->data = 9; node9->next = NULL;
    struct Node * node10 = new Node(); node10->data = 10; node10->next = NULL;

    node1->next = node2;
    node2->next = node3;
    node3->next = node4;
    node4->next = node5;
    node5->next = node6;
    node6->next = node3;

    node7->next = node5;

    printf("%d\n", IsIntersect(node1, node7));
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Yshe_xun/article/details/78390279