[剑指offer]两个链表公共节点

来源:互联网 发布:薇姿适合什么年龄知乎 编辑:程序博客网 时间:2024/06/05 06:35
/*    37:>两个链表公共节点    首先 获取两个链表长度,差值为x,长的先走x步;两个同时走,第一个公共节点即是    O(m+n)*/struct ListNode{    int m_nKey;    ListNode* m_pNext;    ListNode(int val, ListNode* pNode)        :m_nKey(val), m_pNext(pNode)    {}};int GetLength(ListNode* pHead){    if (pHead == NULL)        exit(1);    int count = 0;    ListNode* tmp = pHead;    while (tmp)    {        ++count;        tmp = tmp->m_pNext;    }    return count;}ListNode* FindCommNode(ListNode* pHead1, ListNode* pHead2){    int len1 = GetLength(pHead1);    int len2 = GetLength(pHead2);    int Dif = len1 - len2;    ListNode* pLong = pHead1;    ListNode* pShort = pHead2;    if (len2 > len1)    {        Dif = len2 - len1;        pLong = pHead2;        pShort = pHead1;    }    for (int i = 0; i < Dif; ++i)        pLong = pLong->m_pNext;    while (pLong && pShort && pLong != pShort)    {        pLong = pLong->m_pNext;        pShort = pShort->m_pNext;    }    ListNode* pComm = pLong;    return pLong;}
2 0
原创粉丝点击