判斷兩個鏈表是否相交

解題思路:首先分別判斷兩個鏈表是否存在環。

                   (1)如果兩個鏈表都不存在環,則直接比較兩個鏈表的表尾節點是否相等即可,如果相等,則相交,否則不想交。

                   (2)如果一個鏈表存在環,而另一個鏈表不存在環,則兩個鏈表肯定不相交。

                   (3)如果兩個鏈表都存在環。則如果兩個鏈表相交的話則一個鏈表肯定共用環。通過判斷一個鏈表中任意一個環內節點是否在另一個鏈表中即可判斷兩個鏈表是否相交

 

include "stdafx.h"

  
struct Node
{
    int value;
    Node * next;
};
  
//判斷是否有環,返回bool,如果有環,返回環裏的節點
bool isCircle(Node * head, Node *& circleNode, Node *& lastNode)
{
    Node * fast = head->next;
    Node * slow = head;
    while(fast != slow && fast && slow)
    {
        if(fast->next != NULL)
            fast = fast->next;
  
        if(fast->next == NULL)
            lastNode = fast;
        if(slow->next == NULL)
            lastNode = slow;
  
        fast = fast->next;
        slow = slow->next;
          
    }
    if(fast == slow && fast && slow)
    {
        circleNode = fast;
        return true;
    }
    else
        return false;
}
  
  
bool detect(Node * head1, Node * head2)
{
    Node * circleNode1;
    Node * circleNode2;
    Node * lastNode1;
    Node * lastNode2;
  
    bool isCircle1 = isCircle(head1,circleNode1, lastNode1);
    bool isCircle2 = isCircle(head2,circleNode2, lastNode2);
  
    //一個有環,一個無環
    if(isCircle1 != isCircle2)
        return false;
    //兩個都無環,判斷最後一個節點是否相等
    else if(!isCircle1 && !isCircle2)
    {
        return lastNode1 == lastNode2;
    }
    //兩個都有環,判斷環裏的節點是否能到達另一個鏈表環裏的節點
    else
    {
        Node * temp = circleNode1;
        while(temp != circleNode1)
        {
            if(temp == circleNode2)
                return true;
            temp = temp->next;
        }
        return false;
    }
  
    return false;
}
  
int _tmain(int argc, _TCHAR* argv[])
{
    Node * n1 = new Node();
    Node * n2 = new Node();
    Node * n3 = new Node();
    Node * n4 = new Node();
  
    n1->next = n2;
    n2->next = n3;
    n3->next = n4;
    n4->next = NULL;
  
  
    Node * n5 = new Node();
    Node * n6 = new Node();
    Node * n7 = new Node();
    Node * n8 = new Node();
  
    n5->next = n6;
    n6->next = n7;
    n7->next = n8;
    n8->next = n5;
  
    if(detect(n1,n2))
        printf("相交\n");
    else
        printf("不相交\n");
  
    return 0;
}

 

發佈了32 篇原創文章 · 獲贊 7 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章