链表
两个链表的长度如果相等的话,从头节点开始走,两个指针相等的时候就找到了第一个公共节点。
class Solution { public: ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) { ListNode* L1 = pHead1; ListNode* L2 = pHead2; int l1 = 0,l2 = 0; while(L1 !=NULL || L2!= NULL) { if(L1!=NULL){L1 = L1->next;} else{ l2++; } if(L2 != NULL){L2 = L2->next;} else{ l1++; } } L1 = pHead1; L2 = pHead2; while(l1!=0) { L1 = L1->next; l1--; } while(l2!=0) { L2 = L2->next; l2--; } while(L1!=L2) { L1 = L1->next; L2 = L2->next; } return L1; } };