LeetCodeOJ_160_Intersection of Two Linked Lists

答題鏈接

題目:

Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:
A: a1 → a2

c1 → c2 → c3

B: b1 → b2 → b3
begin to intersect at node c1.

Notes:
•If the two linked lists have no intersection at all, return null.
•The linked lists must retain their original structure after the function returns.
•You may assume there are no cycles anywhere in the entire linked structure.
•Your code should preferably run in O(n) time and use only O(1) memory.

分析:

從交叉點開始,到鏈表末尾,兩個鏈表的長度是一樣的。

代碼:

/**
 * 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 *intersection=NULL;
        if(headA==NULL||headB==NULL)
            return intersection;

        //統計鏈表A的長度
        ListNode * curNodeA=NULL;
        int lenA=0;
        curNodeA=headA;
        while(curNodeA!=NULL)
        {
            curNodeA=curNodeA->next;
            lenA++;
        }
        //統計鏈表B的長度
        ListNode * curNodeB=NULL;
        int lenB=0;
        curNodeB=headB;
        while(curNodeB!=NULL)
        {
            curNodeB=curNodeB->next;
            lenB++;
        }
        //定位起始比較點
        curNodeA=headA;
        curNodeB=headB;
        if(lenA>lenB)
        {
            for(int i=0;i<(lenA-lenB);i++)
            {
                curNodeA=curNodeA->next;
            }
        }
        else if(lenA<lenB)
        {
            for(int i=0;i<(lenB-lenA);i++)
            {
                curNodeB=curNodeB->next;
            }
        }
        //尋找交叉點
        while(curNodeA->val!=curNodeB->val||curNodeA->next!=curNodeB->next)
           {
               curNodeA=curNodeA->next;
               curNodeB=curNodeB->next;
               if(curNodeA==NULL)
                  break;
           }
           intersection=curNodeA;

        return intersection;

    }
};

結果:

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章