题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
思路:1、分别遍历两个链表,记录两个链表的长度,尾结点相同就是相交,否则就不相交 2、求第一个交点:长的链表先走(长度差)步,再同时走,第一个相同就是交点 struct ListNode* FindFirstCommonNode(struct ListNode* pHead1, struct ListNode* pHead2 ) { struct ListNode* tail1 = pHead1; struct ListNode* tail2 = pHead2; int len1 = 1; int len2 = 1; while(tail1) { tail1 = tail1->next; len1++; } while(tail2) { tail2 = tail2->next; len2++; } if(tail1 != tail2) return NULL; int len = abs(len1-len2); struct ListNode* longlist = pHead1; struct ListNode* shortlist = pHead2; if(len1 < len2) { longlist = pHead2; shortlist = pHead1; } while(len--) { longlist = longlist->next; } while(longlist != shortlist) { longlist = longlist->next; shortlist = shortlist->next; } return longlist; }