lintcode ----两个链表的交叉

来源:互联网 发布:淘宝店铺怎么来搞信誉 编辑:程序博客网 时间:2024/04/30 09:28

想法遍历两个链表到最后,判断连个链表最后的位置是否相同,不同直接返回;用两个变量记录链表的长度,哪个长    先往后遍历到一样长,接着另一个也开始同时遍历,直到相等,返回头指针



 ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)     {        // write your code here        if(headA==NULL||headB==NULL)            return NULL;        ListNode *p = headA;        ListNode *q = headB;        int a=1,b=1;        while(p->next!=NULL)        {            p=p->next;            a+=1;        }        while(q->next!=NULL)        {            q=q->next;            b+=1;        }        if(q!=p)            return NULL;        if(a>b)        {            for(int i=0;i<a-b;i++)            {                headA=headA->next;            }        }        else if(a<b)        {            for(int j=0;j<b-a;j++)            {                headB=headB->next;            }        }        while(headA!=headB)        {            headA=headA->next;            headB=headB->next;        }        return headA;    }


0 0
原创粉丝点击