1. Topic description:
Enter two linked lists and find their first common node.
class Solution {
public:
ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2) {
/*参考大佬*/
if (pHead1==NULL||pHead2==NULL)
{
return NULL;
}
ListNode*p1 = pHead1;
ListNode*p2 = pHead2;
while (p1!=p2)
{
p1 = (p1 == NULL) ? pHead2 : p1->next;//第一趟走完走p2
p2 = (p2 == NULL) ? pHead1 : p2->next;//第一场走完走p1,到第一个相同点时,走过路径的长度相等,
}
return p1;
}
};
ps: Refer to the big guy's solution, the idea is very good, cleverly solve the linked list with different lengths without traversing the length of the linked list, and a similar problem is to use two pointers with different steps to find out whether it is a circular linked list ,