0
点赞
收藏
分享

微信扫一扫

链表相交---leetcode面试题 02.07

 

 这道题主要难点在于没读懂题,反正看网上意思就是把两个链表先尾部对齐后,找相交的起始节点。

第一种方法:指针法

class Solution {
public:
    int getlength(ListNode* head)
    {
        int length = 0;
        while(head != NULL)
        {
            length++;
            head = head->next;  
        }
        return length;
    }
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        int lengthA = getlength(headA);
        int lengthB = getlength(headB);
        ListNode* curA = headA;
        ListNode* curB = headB;
        if(lengthA > lengthB)
        {
            for(int i = 0;i< (lengthA - lengthB);i++)
            {
                curA = curA->next;
            }
        }else if(lengthA < lengthB)
        {
            for(int i = 0;i< (lengthB - lengthA);i++)
            {
                curB = curB->next;
            }
        }
        while(curA != NULL)
        {
            if(curA == curB){
                return curA;
            }
            curA = curA->next;
            curB = curB->next;
        }
        return NULL;        
    }
};
举报

相关推荐

0 条评论