题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://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==nullptr||pHead2==nullptr) return nullptr;
vector<ListNode*>stack1,stack2;
while(pHead1!=nullptr){
stack1.push_back(pHead1);
pHead1=pHead1->next;
}
while(pHead2!=nullptr){
stack2.push_back(pHead2);
pHead2=pHead2->next;
}
int i=0;
while(1){
if(i==stack1.size()||i==stack2.size()) break;
if(stack1[stack1.size()-i-1]==stack2[stack2.size()-i-1]){
i++;
}
else{
return stack1[stack1.size()-i];
}
}
return stack1[stack1.size()-i];
}
};
查看10道真题和解析