找出两个链表的第一个公共节点

来源:互联网 发布:不该 周杰伦 知乎 编辑:程序博客网 时间:2024/06/05 10:26

思路:

两个链表的第一个公共节点即同一个节点,因为链表的遍历都是从头开始,因此如果两个链表的长度相等,只要同步遍历即可得到第一个共同节点;

代码如下:

    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {        if(pHead1==NULL || pHead2==NULL)            return NULL;        int length1=GetListLength(pHead1);        int length2=GetListLength(pHead2);        ListNode* pLong=pHead1;        ListNode* pShort=pHead2;        int k=length1-length2;        if(length1<length2){            k=length2-length1;            pLong=pHead2;            pShort=pHead1;        }        while(k>0){            pLong=pLong->next;            k--;        }        while(pLong && pShort&& pLong!=pShort){            pLong=pLong->next;            pShort=pShort->next;        }        if(pLong!=NULL&&pShort!=NULL)            return pLong;        return NULL;    }    int GetListLength(ListNode* root){        int count=0;        while(root!=NULL){            root=root->next;            count++;        }        return count;    }


阅读全文
0 0
原创粉丝点击