"Daily Question" Interview Question 02.07. Intersection of Linked Lists

 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        ListNode* dheada = new ListNode(0);
        ListNode* dheadb = new ListNode(0);
        dheada->next = headA;
        dheadb->next = headB;
        ListNode* cur1 = dheada;
        ListNode* cur2 = dheadb;
        int cnt1 = 0, cnt2 = 0; 
        while (cur1 != NULL){
            cur1 = cur1->next;
            cnt1++; 
        }//查找链表1的长度
        while (cur2 != NULL){
            cur2 = cur2->next;
            cnt2++;
        }//查找链表2的长度
        cur1 = dheada;
        cur2 = dheadb;
        while (cur1 != NULL || cur2 !=NULL){
            if (cnt1 == cnt2){
                if (cur1 == cur2){
                    return cur1;
                }//查找相交点,指针相同而不是值相同
                else {
                    cur1 = cur1->next;
                    cur2 = cur2->next;
                }
            }
            else if (cnt1 > cnt2){
                cur1 = cur1->next;
                cnt1--;
            }//调整到末端对齐
            else {
                cur2 = cur2->next;
                cnt2--;
            }
        }
        return NULL;
    }
};

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324517151&siteId=291194637