码迷,mamicode.com
首页 > 编程语言 > 详细

经典算法学习——打印两个链表的第一个公共节点

时间:2016-08-21 21:24:14      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:

       求链表的公共节点是一道很经典的算法题,并不是很难。我们需要知道的是,一旦两个链表有一个公共节点的话,那么这两个链表的形状就是一个“Y”型。也就是说,自公共节点之后的所有节点都是一样的。如下:

技术分享


其实只要看了这幅图,实现就很简单了。首先我们分别遍历两个链表,分别得出他们的长度L1,L2。然后在查找公共节点时,先在长的那个链表中走|L1-L2|步,然后两个链表同时向后进行同步遍历,每走一步时,就判断后面那个节点是否相同。若相同,则找到该第一个公共节点。完整代码上传至 https://github.com/chenyufeng1991/TwoListSameNode  。

核心代码如下:

void PrintSameNode(Node *pFirstList, Node *pSecondList)
{
    int pFirstListLength = ListLength(pFirstList);
    int pSecondListLength = ListLength(pSecondList);

    Node *pFirstMove = pFirstList->next;
    Node *pSecondMove = pSecondList->next;

    if (pFirstListLength > pSecondListLength)
    {
        int startStep = pFirstListLength - pSecondListLength;
        while (startStep--)
        {
            pFirstMove = pFirstMove->next;
        }
    }
    else if (pFirstListLength == pSecondListLength)
    {

    }
    else
    {
        int startStep = pSecondListLength - pFirstListLength;
        while (startStep--)
        {
            pSecondMove = pSecondMove->next;
        }
    }

    while (pFirstMove != pSecondMove)
    {
        pFirstMove = pFirstMove->next;
        pSecondMove = pSecondMove->next;
    }

    if (pFirstMove == pSecondMove)
    {
        cout << "第一个公共节点为:" << pFirstMove->element <<endl;
    }

    return;
}


经典算法学习——打印两个链表的第一个公共节点

标签:

原文地址:http://blog.csdn.net/chenyufeng1991/article/details/52269135

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!