面试题:两个链表的第一个公共结点

题目描述: 输入两个链表,求他们的第一个公共结点。
(图中内容不是测试用例的数字)
这里写图片描述
第一种思路描述:

  1. 首先遍历两个链表,得到其长度gap
  2. 接着,让较长的链表先走gap步
  3. 两个链表同时走,此时找到的第一个公共结点就是所需结点

    时间复杂度O(m+n)
    代码实现:

//此处借用了链表的头文件
//获取链表长度
int GetListLength(SListNode* list)
{
    assert(list);
    int count = 0;
    SListNode* node = list;
    while (node != NULL)
    {
        count++;
        node = node->_next;

    }
    return count;
}

SListNode* FindFirstCommonNode(SListNode* list1, SListNode* list2)
{
    {
        SListNode* longlist = NULL;
        SListNode* shortlist = NULL;
        SListNode* cur1 = list1;
        SListNode* cur2 = list2;
        int n1 =GetListLength(cur1);
        int n2 = GetListLength(cur2);
        int gap = 0;

        longlist = list1;
        shortlist = list2;

        //比较两个链表的大小
        if (n1 < n2)
        {
            longlist = list2;
            shortlist = list1;
        }
        gap = abs(n1 - n2);//绝对值
        //长链表先走gap步,短链表,长链表再同时继续走
        while (gap--)
        {
            longlist = longlist->_next;
        }
        while (shortlist != longlist)
        {
            shortlist = shortlist->_next;
            longlist = longlist->_next;
        }
        return shortlist;
    }
}
int main()
{
    SListNode* node11, *node22;
    SListNode* node1 = BuySListNode(1);
    SListNode* node2 = BuySListNode(2);
    SListNode* node3 = BuySListNode(3);
    SListNode* node4 = BuySListNode(4);
    SListNode* node5 = BuySListNode(5);
    node1->_next = node2;
    node2->_next = node3;
    node3->_next = node4;
    node4->_next = node5;

    node11 = BuySListNode(11);
    node22 = BuySListNode(22);
    node11->_next = node22;
    node22->_next = node4;

    printf("Cross Node? %d\n", FindFirstCommonNode(node1,node11)->_data);
    system("pause");
    return 0;
}

截图我就不粘贴了,结果为4,。

同样也可借助栈实现,时间复杂度也是O(m+n),不过空间效率较上者低。
第二种思路:分别将两个链表放入两个栈里,此时两个链表的尾结点位于栈顶,接下来比较结点是否相同,如果相同,弹出,接着比较下一个结点,直至找到最后一个相同的结点,打印之。,空间复杂度O(m+n).相当于用空间换取时间。

猜你喜欢

转载自blog.csdn.net/kai29/article/details/79838208