题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * * @param pHead1 ListNode类 * @param pHead2 ListNode类 * @return ListNode类 */ struct ListNode* FindFirstCommonNode(struct ListNode* pHead1, struct ListNode* pHead2 ) { // write code here struct ListNode* pHead1temp = pHead1; struct ListNode* pHead2temp = pHead2; while (NULL != pHead1temp) { pHead2temp = pHead2; //snowshuang : 开始这里忘记每次都要从头开始遍历忘记加了导致运行不符合预期,如果用for循环应该不会出现这个问题,因为for循环里面赋初值。 while (NULL != pHead2temp) { if (pHead1temp == pHead2temp) { return pHead1temp; } printf("pHead2temp->val = %d, pHead1temp->val = %d\r\n", pHead2temp->val, pHead1temp->val); pHead2temp = pHead2temp->next; } //printf("pHead1temp->val = %d\r\n", pHead1temp->val); pHead1temp = pHead1temp->next; } return NULL; }