题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46?tpId=295&tqId=23257&ru=/exam/company&qru=/ta/format-top101/question-ranking&sourceUrl=%2Fexam%2Fcompany
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * * @param pHead1 ListNode类 * @param pHead2 ListNode类 * @return ListNode类 */ #include <stdio.h> struct ListNode* FindFirstCommonNode(struct ListNode* pHead1, struct ListNode* pHead2 ) { // write code here if(pHead1 == NULL || pHead2 == NULL) return NULL; struct ListNode *p1=pHead1; struct ListNode *p2=pHead2; while(p1 != p2) { if(p1 == NULL) p1=pHead2; else p1=p1->next; if(p2 == NULL) p2=pHead1; else p2=p2->next; } return p2; }
记录:两个链表的长度不同,那么分别遍历两个链表,当一个链表遍历完毕指向NULL后,让他指向对应的另一个链表继续遍历,这样总会有一次当两个链表相等的时候,这个时候则是两个链表的公共节点开始的节点