Question: enter two linked lists to find their first public node.
If the two linked lists have public nodes, the public nodes must appear at the end of the two linked lists.
If the two linked lists are not of the same length, the number of steps to reach the public node is inconsistent. How can we ensure that the two linked lists are traversed from the beginning and synchronized to the public node? This is the key
If the two linked lists have the same length, what can they be synchronized? Therefore, we need to make the two linked lists have the same length"
Let's assume that the two linked lists are respectively M and N, and m> N, then we can take steps m-N first in a long chain table, and then the two linked lists are synchronized, if there are public nodes
ListNode* FirstCommonNode(ListNode* list1, ListNode* list2){ if (list1 == NULL || list2 == NULL) return NULL; ListNode* cur1 = list1; ListNode* cur2 = list2; int list1Len = 0; int list2Len = 0; while (cur1++ != NULL) { ++list1Len; } while (cur2++ != NULL) { ++list2Len; } int maxLen = std::max(list1Len, list2Len); ListNode* longerList = NULL; ListNode* shorterList = NULL; int gap = 0; if (maxLen == list1Len) { longerList = list1; shorterList = list2; gap = maxLen - list2Len; } else { longerList = list2; shorterList = list1; gap = maxLen - list1Len; } int firstStep = 0; while (firstStep != gap) { longerList = longerList->next; ++firstStep; } while (longerList != NULL && shorterList != NULL) { if (longerList == shorterList) { return longerList; } else { longerList = longerList->next; shorterList = shorterList->next; } } return NULL;}