将两个链表倒过来比较,如果元素相同则继续比较,直到遇到不是相同的元素时退出循环。这里使用stack来将链表倒过来。

/*
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*> head1_stack;
        stack<ListNode*> head2_stack;

        ListNode* p = pHead1;
        while(p)
        {
            head1_stack.push(p);
            p = p->next;
        }

        ListNode* q = pHead2;
        while(q)
        {
            head2_stack.push(q);
            q = q->next;
        }

        ListNode* rst = NULL;
        while(!head1_stack.empty() && !head2_stack.empty())
        {
            if(head1_stack.top() == head2_stack.top())
            {
                rst = head1_stack.top();
                head1_stack.pop();
                head2_stack.pop();
            }else
            {
                break;
            }
        }

        return rst;
    }
};