/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
//创建两个节点->两个链表
ListNode* l1 = pHead1;
ListNode* l2 = pHead2;
while(l1 != l2)
{
//到链表结尾时遍历另一个链表,直到每个链表都被遍历两遍
l1 = (l1 == NULL)?pHead2:l1->next;
l2 = (l2 == NULL)?pHead1:l2->next;
}
//当有公共节点时,直接返回从公共节点到链表结尾的公共链表
//无公共节点时因为遍历到链表结尾结果为NULL,也可返回l1
return l1;
}
};

京公网安备 11010502036488号