LeetCode 160. Intersection of Two 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) {
        
       int lenA = fun(headA);
       int lenB = fun(headB);
        
       int posA=lenA;
       int posB=lenB;
        
        ListNode* termA = headA;
        ListNode* termB = headB;
        
        ListNode* ans=NULL;
        
        while(termA!=NULL&&termB!=NULL)
        {
            if(posA<posB)
            {
                termB=termB->next;
                posB--;
                continue;
            }
            else if(posA>posB)
            {
                termA=termA->next;
                posA--;
            }
            else
            {
                if(termA==termB)
                {
                    ans=termA;
                    break;
                }
                
                termA=termA->next;
                termB=termB->next;
            }
        }
        
        return ans;
        
    }
    
    int fun(ListNode* head)
    {
        int ans=0;
        ListNode* term = head;
        while(term!=NULL)
        {
            ans++;
            term=term->next;
        }
        
        return ans;
    }
    
    
};
posted @ 2020-01-21 13:32  Shendu.CC  阅读(76)  评论(0编辑  收藏  举报