微软面试题<七>

来源:互联网 发布:网络荐股 编辑:程序博客网 时间:2024/06/05 00:43

题目:

微软亚院之编程判断俩个链表是否相交:
给出俩个单向链表的头指针,比如h1,h2,判断这俩个链表是否相交。
为了简化问题,我们假设俩个链表均不带环。
问题扩展:
1.如果链表可能有环列?
2.如果需要求出俩个链表相交的第一个节点列?


先来解决两链表均不带环的情况:

需要注意的是链表相交不是指链表含有相同的元素,而是地址相同.通过此图可以发现

判断两个链表是否相交 - 枫叶 - 枫叶

相交的两个链表其最后一个元素的地址必相同,所以可以遍历两链表至尾结点,然后比较得出结果.

代码实现:

//判断两链表(均不带环)是否相交#include<iostream>#include<cmath>using namespace std;struct ListNode{       int data;       ListNode *next;};void CreateList(ListNode *&root){     cout<<"建立链表,输入零代表结束!"<<endl;      int value;     ListNode *last=new ListNode;     last=NULL;     while(1)      {       cin>>value;       if(value==0) break;       ListNode *newnode=new ListNode;       newnode->data=value;       newnode->next=NULL;       if(root==NULL)       { root=newnode; last=newnode;}       else       {           last->next=newnode;           last=newnode;       }     }}void Travel(ListNode *root){     while(root!=NULL)     {      cout<<root->data<<"  address="<<root<<endl;      root=root->next;     }}bool Find(ListNode *root1,ListNode *root2){   //判断相交,直接看最后一个元素的地址是否相同   int len1=1,len2=1,k;   ListNode *pHead1=new ListNode;   ListNode *pHead2=new ListNode;   pHead1=pHead2=NULL;   pHead1=root1; pHead2=root2;   while(pHead1->next) { len1++; pHead1=pHead1->next; }   while(pHead2->next) { len2++; pHead2=pHead2->next; }   if(pHead1!=pHead2) return false;   else   {       cout<<"两链表相交!"<<endl;       //下面寻找第一个相交的点        k=abs(len1-len2);       pHead1=root1; pHead2=root2;       if(len1<len2) //如果第一个链表长一些        {         while(k--) pHead2=pHead2->next;         while(pHead1!=pHead2)          {           pHead1=pHead1->next; pHead2=pHead2->next;                              }        cout<<"第一个相交的点是"<<pHead1->data<<" address="<<pHead1<<endl;       }       else if(len1>=len2)       {            while(k--)            pHead1=pHead1->next;            while(pHead1!=pHead2)            {            pHead1=pHead1->next; pHead2=pHead2->next;                                 }        cout<<"第一个相交的点是"<<pHead1->data<<" address="<<pHead1<<endl;       }       return true;    } }  int main(){    ListNode *root1=new ListNode;    ListNode *root2=new ListNode;    ListNode *p=new ListNode;    ListNode *q=new ListNode;    int i=4;    p=q=root1=root2=NULL;    CreateList(root1);    cout<<"The First List as follows"<<endl;     Travel(root1);    CreateList(root2);    //构造第二个链表,先遍历到尾节点     p=root2;    q=root1;    while(p->next) p=p->next;    while(i--) q=q->next;    p->next=q;    cout<<"The Secone list"<<endl;    Travel(root2);    cout<<"The Result"<<endl;    Find(root1,root2);    system("pause");    return 0;}