The sword refers to the first public node of the offer (37) Two linked lists.

Source: Internet
Author: User

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;}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.