/*
struct ListNode {
    int val;
    struct ListNode next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};/
class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        //首先要理解公共结点的意思是什么;公共部分一定出现在尾部,用两个栈从后往前遍历,
        //找到第一个不相等的结点,其前一个结点就是第一个公共结点
        stack<ListNode> stk1, stk2;
        ListNode res = nullptr;
        //入栈
        while(pHead1 != nullptr)
        {
            stk1.push(pHead1);
            pHead1 = pHead1->next;
        }
        while(pHead2 != nullptr)
        {
            stk2.push(pHead2);
            pHead2 = pHead2->next;
        }
        //比较两个栈的栈顶元素,相等就保存下来,不等就说明上一个保存的结点是第一个公共结点
        while(!stk1.empty() && !stk2.empty())
        {
            if(stk1.top() == stk2.top())
            {
                res = stk1.top();
                stk1.pop();
                stk2.pop();
            }else{
                break;
            }
        }
        return res;
    }
};

京公网安备 11010502036488号