题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
http://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
// 不太聪明的亚子,用了栈 /* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) { if(!pHead1 || !pHead2) { return nullptr; } stack<ListNode*> sta1; stack<ListNode*> sta2; while(pHead1) { sta1.push(pHead1); pHead1 = pHead1->next; } while(pHead2) { sta2.push(pHead2); pHead2 = pHead2->next; } ListNode* node = nullptr; while(!sta1.empty() && !sta2.empty()) { if(sta1.top() == sta2.top()) { node = sta1.top(); } sta1.pop(); sta2.pop(); } return node; } };