题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
找到了公共结点,那么该结点之后的结点在两个链表中是完全相同的,所以先计算两个链表的长度,让长的链表指针向前移动length'2-length1的距离,之后再让两个指针一同向前移动,找到了公共结点后也就找到了公共位置的起始结点。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
*
* @param pHead1 ListNode类
* @param pHead2 ListNode类
* @return ListNode类
*/
// 计算长度
int getLength(struct ListNode* pHead){
struct ListNode* list_test = pHead;
int length = 1;
while(list_test!=NULL){
length++;
list_test = list_test->next;
}
return length;
}
struct ListNode* FindFirstCommonNode(struct ListNode* pHead1, struct ListNode* pHead2 ) {
// write code here
int length1,lenght2,i=0;
struct ListNode* p1 = pHead1;
struct ListNode* p2 = pHead2;
length1 = getLength(p1);
lenght2 = getLength(p2);
if(length1>lenght2) while (i<length1-lenght2) {
i++;
p1 = p1->next;
} else while(i<lenght2-length1){
i++;
p2 = p2->next;
}
while(p1!=NULL && p2!=NULL && p1!=p2){
p1 = p1->next;
p2 = p2->next;
}
if(p1 == p2) return p1;
else return NULL;
}
