示例1
输入:
{1,2,3},{4,5},{6,7}
返回值:
{6,7}
说明:
第一个参数{1,2,3}代表是第一个链表非公共部分,第二个参数{4,5}代表是第二个链表非公共部分,最后的{6,7}表示的是2个链表的公共部分
这3个参数最后在后台会组装成为2个两个无环的单链表,且是有公共节点的
示例2
输入:
{1},{2,3},{}
返回值:
{}
说明:
2个链表没有公共节点 ,返回null,后台打印{}
解题思路
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*
* C语言声明定义全局变量请加上static,防止重复定义
*/
/**
*
* @param pHead1 ListNode类
* @param pHead2 ListNode类
* @return ListNode类
*/
struct ListNode* FindFirstCommonNode(struct ListNode* pHead1,
struct ListNode* pHead2 ) {
// write code here
// pHead1 or pHead2 is null
if (pHead1 == NULL || pHead2 == NULL) {
return NULL;
}
// same speed, same length, so must be meet in after.
struct ListNode* move1 = pHead1;
struct ListNode* move2 = pHead2;
while (move1->val != move2->val) {
move1 = move1->next;
move2 = move2->next;
// no pn, when both are null
if (move1 == NULL && move2 == NULL) {
return NULL;
}
if (move1 == NULL) {
move1 = pHead2;
}
if (move2 == NULL) {
move2 = pHead1;
}
}
return move1;
}