【剑指offer系列】 两个链表的第一个公共节点___37

来源:互联网 发布:霍尔果斯万游网络 编辑:程序博客网 时间:2024/05/17 04:34

  题目描述:
  输入两个单链表,找出他们的第一个公共节点。若没有,则返回NULL   
  
  分析:
  如果两个单链表有公共节点,那么在交点后的每一个节点都是公共的。因此两个单链表的构型必然是下图所示的Y型。
  这里写图片描述 
  1)利用栈的先进后出,将两个链表的所有节点都入栈。然后再依次出栈。找出最后一个相同节点,即为第一个公共节点.但是这种方法需要两个栈作为辅助空间
  2)首先我们可以分别遍历两个链表,得到其长度len1和len2。然后使用快慢指针,使较长链表的指针先走len1-len2步,然后两个指针同时每次走一步。当两个指针相遇时,即为第一个公共节点
  
  代码:   

int getListLength(listNode *head){    listNode *p=head;    int len=0;    while(p){        ++len;        p=p->next;    }    return len;}listNode *firstCommon(listNode *head1,listNode *head2){    int len1=getListLength(head1);    int len2=getListLength(head2);    if(len1==0||len2==0)    return NULL;    listNode *p=head1,*q=head2;    while(len1>len2){        p=p->next;        --len1;    }    while(len1<len2){        q=q->next;        --len2;    }    while(p&&q&&p!=q){        p=p->next;        q=q->next;    }    return p;}
0 0