题解 | #两个链表的第一个公共结点(优化)#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
//时间复杂度O(m+n)两个指针轮流走,必定会相遇
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
ListNode* temp1 = pHead1;
ListNode* temp2 = pHead2;
if(temp1==NULL||temp2==NULL){
return NULL;
}
while(temp1 != temp2){
if (temp1 ==NULL){
temp1= pHead2; //这已经相当于走了一步,不应该再走了
continue;
}
if(temp2 ==NULL){
temp2 = pHead1;
continue;
}
temp1= temp1 ->next;
temp2 = temp2 ->next;
}
return temp1;
}
};
查看1道真题和解析
