判断两个链表是否相交

方法:获得两个链表的长度,获得长度的差值len,然后首先遍历较长的链表len次,然后再同时遍历两个链表,如果有相同部分,两个链表就相交,如果没有,则不相交,即没有公共部分。

代码:

 

#include <iostream>

#include <cstdlib>

using namespace std;



typedef struct list{

     int data;

     struct list *next;

}*listNode;

void initList(listNode &list)                     //初始化程序

{

     list=(struct list*)malloc(sizeof(struct list));

     list->data=0;

     list->next=NULL;

}



void createList(listNode &list,int a[],int n)        //创建链表

{

    listNode head,node;

    head=list;

    for(int i=0;i<n;i++)

      {

         node=(struct list*)malloc(sizeof(struct list));

         node->data=a[i];

         node->next=NULL;

         head->next=node;

         head=node;

      }

    

}

void judgeInter(listNode list,listNode list1)           //判断两个链表是否相交

{

    int len1=0,len2=0;

    listNode head,head1;

    head=list->next;

    //获得两个链表的长度

    while(head)

    {

       len1++;

       head=head->next;

    }

    head=list1->next;

    while(head)

    {

      len2++;

      head=head->next;

    }

    int t=len1-len2;

    head=list;

    head1=list1;

    while(t>0)

    {

       head=head->next;

       t--;

    }

    while(len2>0)    //判断有没有相同的部分

    {

      head=head->next;

      head1=head1->next;

      if(head->data==head1->data)

       {

           cout<<"the two list have the same part:"<<" "<<head->data<<endl;

           break;

       }

      len2--;

    }

    if(len2<=0)

       cout<<"the two list dont have the same list"<<endl;

}

void playList(listNode list)      //输出单链表

{

    listNode head;

    head=list->next;

    if(head==NULL)

       cout<<"the list is null"<<endl;

    while(head)

     {

       cout<<head->data<<"--";

       head=head->next;

     }

   cout<<endl; 

}



int main()

{

    listNode list,list1;

    int a[10]={1,2,3,4,5,6,7,8,9,0};

    int b[8]={12,13,16,17,11,8,9,0};

    initList(list);

    initList(list1);

    cout<<"create the list:"<<endl;

    createList(list,a,10);

    createList(list1,b,8);

    cout<<"output the list:"<<endl;

    playList(list);

    playList(list1);

    cout<<endl;

    judgeInter(list,list1);

    cout<<endl;

    return 0;

}

运行截图:

判断两个链表是否相交

你可能感兴趣的:(链表)