码迷,mamicode.com
首页 > 其他好文 > 详细

【剑指offer】52、两个链表的第一个公共节点

时间:2018-07-22 00:29:10      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:nbsp   i++   for   head   fir   while   first   一起   nullptr   

题目

输入两个链表,找出它们的第一个公共结点。

思路一

因为是反向找,所以会想到用栈。将两个链表都压入两个栈,然后反向弹出,找出第一个公共节点。思路很简单

class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        stack<ListNode*> s1, s2;
        if (pHead1 == nullptr || pHead2 == nullptr)
            return nullptr;
        while (pHead1 != nullptr)
        {
            s1.push(pHead1);
            pHead1 = pHead1->next;
        }
        while (pHead2 != nullptr)
        {
            s2.push(pHead2);
            pHead2 = pHead2->next;
        }
        ListNode* common = nullptr;
        while (s1.size() && s2.size())
        {
            if (s1.top() == s2.top())
                common = s1.top();
            s1.pop();
            s2.pop();
        }
        return common;
    }
};

思路二

链表这种问题往往可以用快慢指针,先统计出两个链表的长度l1,l2

然后让长一点的链表从头节点先走 |l1-l2|,然后两个指针一起走,第一个相同的就是公共节点

class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        if ( pHead1 == nullptr || pHead2 == nullptr)
            return nullptr;
        int len1 = ListLength(pHead1);
        int len2 = ListLength(pHead2);
         
        ListNode* longer = pHead1;
        ListNode* shorter = pHead2;
         
        for (int i = 1; i <= abs(len1 - len2);i++)
            len1 > len2?longer = longer->next: shorter = shorter->next;
        
        while (longer != shorter && shorter && longer)
        {
            longer = longer->next;
            shorter = shorter->next;
        }
        return longer; // 当两个没有公共节点时,会返回尾结点,正好是nullptr
         
    }
    int ListLength(ListNode* pHead){
        ListNode* pre = pHead;
        int count = 0;
        while (pre != nullptr)
        {
            count++;
            pre = pre->next;
        }
        return count;
    }
};

 

【剑指offer】52、两个链表的第一个公共节点

标签:nbsp   i++   for   head   fir   while   first   一起   nullptr   

原文地址:https://www.cnblogs.com/shiganquan/p/9348410.html

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