俊介三

一天更新一点,一天积累一点

导航

判断俩个链表是否相交

Posted on 2013-03-28 09:52  俊介三在前进  阅读(128)  评论(0编辑  收藏  举报

给出两个单向链表的头指针,比如h1,h2,判断这俩个链表是否相交.(注意要考虑此链是否带环)

#include <stdio.h>
#include <stdlib.h>

struct List{
    int data;
    List* next;
    List(){}
    List(int d){
        data = d;
        next = NULL;
    }
    List(int d, List* list){
        data =d;
        next = list;
    }
};

//append an element to tail
List* appendToTail(int data, List* head){
    List* tail = new List(data,NULL);
    List* p = head;
    while(p->next!=NULL){
        p = p->next;
    }
    p->next = tail;
    return head;
}

//测试是否为环
List* cyclic(List* h){
    List* l1 = h;
    List* l2 = h;
    while(l1!=NULL && l2->next!=NULL){
        l1 = l1->next;
        l2 = l2->next->next;
        if(l1==l2) return l1;
    }
    return 0;
}

bool isJoined(List* h1, List* h2){
    List* head2 = h2;
    h1 = cyclic(h1);
    h2 = cyclic(h2);

    //其一是环,则没有交点
    if(h1==0&&h2!=0 || h1!=0&&h2==0) return false;
    
    //如果都不是环的情况
    if(h1!=0 && h2!=0){
        while(h1->next!=NULL) h1=h1->next;
        while(h2->next!=NULL) h2=h2->next;
        return (h1==h2)?true:false;
    }

    //都是环的情况
    else{
        while(head2->next!=NULL){
            if(h1==head2) return true;
            head2 = head2->next;
        }
        return false;
    }
}

int main(){
    List* node = new List(12);
    List* head = appendToTail(23,node);
    head = appendToTail(14,head);
    
    List* node2 = new List(12);

    printf("node1 and node2 is %sjoined\n",isJoined(node,node2)?"":"not ");

    return 0;
}