LeetCode160. Intersection of Two Linked Lists [C++]

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

For example, the following two linked lists:

begin to intersect at node c1.

Example 1:

Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
Output: Reference of the node with value = 8
Input Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,0,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.

解题思路:

1.遍历链表A和B,得到A、B的长度。

2.利用长度,将A、B对齐。

3.对齐后,A、B逐个判断。

满足时间O(n)

/**
 * 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* curA=headA;
        ListNode* curB=headB;
        int lenA=0,lenB=0;
        while(curA!=NULL)
        {
            lenA++;
            curA=curA->next;
        }
        while(curB!=NULL)
        {
            lenB++;
            curB=curB->next;
        }
        int sub=lenA-lenB;
        curA=headA;
        curB=headB;
        if(sub>0)
        {
            while(sub--)
                curA=curA->next;
        }
        else
        {
            sub=abs(sub);
            while(sub--)
                curB=curB->next;
        }
        while(curA!=NULL)
        {
            if(curA==curB)
                break;
            curA=curA->next;
            curB=curB->next;
        }
        return curA;
    }
};

猜你喜欢

转载自blog.csdn.net/ueh286/article/details/91868010