判断链表有公共点

判断两个链表是否相汇,可以通过将第一个链表的尾部与第二个链表的头部相连接,如果链表形成了环,则说明链表相汇了。

/*
* 两个链表是否公共结点
*/
#include<iostream>
#include<ctime>
#include<cstdlib>
#include<cstdio>
using namespace std;
typedef struct node* link;
typedef struct node{
    int value;
    link next;
    node(){
        value=-1;
        next=NULL;
    }
    node(int v){
        value=v;
        next=NULL;
    }
}Node;

void GenerateList(link& head1,link& head2){
    int n=rand()%100+1;
    head1=new Node();
    head2=new Node();
    link p1=head1,p2=head2;
    for(int i=0;i<n;i++){
        int x=rand()%100+1;
        p1->next=new Node(x);
        p1=p1->next;
    }
    int m=rand()%100+1;
    for(int i=0;i<m;i++){
        int x=rand()%100+1;
        p2->next=new Node(x);
        p2=p2->next;
    }
    p1->next=p2;  //if this statement is deleted, the two lists will have no common points;
    printf("the random common point's address:%d\n",p2);
    int k=rand()%100+1;
    for(int i=0;i<k;i++){
        int x=rand()%100+1;
        p2->next=new Node(x);
        p2=p2->next;
    }
    head1->value=n+k+1;
    head2->value=m+k;
}

bool FindCircle(link head){
    link p=head;
    while(p->next!=NULL){
        p=p->next;
        if(p==head){
            return true;
        }
    }
    return false;
}

int main(){
    srand((unsigned)time(NULL));
    link head1=NULL,head2=NULL;
    GenerateList(head1,head2);

    // connect tail of list1 to the head of list2
    link p=head1;
    while(p->next!=NULL) p=p->next;
    p->next=head2;

    //judge whether there exists a circle
    if(FindCircle(head2)){
        if(head1->value<head2->value){
            int count=head2->value-head1->value;
            while(count--){
                head2=head2->next;
            }
        }else{
            int count=head1->value-head2->value;
            while(count--){
                head1=head1->next;
            }
        }
        while(head1!=head2){
            head1=head1->next;
            head2=head2->next;
        }
        printf("the common point's address:%d\n",head1);
    }else{
        printf("No common nodes\n");
    }
    return 0;
}
posted @ 2018-04-04 00:16  fenicnn  阅读(139)  评论(0编辑  收藏  举报