【C++】求两个链表的交点

方法一,使用C++的set库

  • set的使用方法:
int main() {
    
    
    set<int> setA;
    const int lenA = 7;
    const int lenB = 8;

    int a[lenA] = {
    
     5,1,4,8,10,1,3 };
    int b[lenB] = {
    
     2,7,6,3,1,6,0,1 };
    for (int i = 0; i < lenA; i++)
    {
    
    
        setA.insert(a[i]);
    }
    for (int i = 0; i < lenB; i++)
    {
    
    
        if (setA.find(b[i])!=setA.end())
            printf("b[%d] = %d in array A.\n", i, b[i]);
    }
    return 0;
}

结果:

b[3] = 3 in array A.
b[4] = 1 in array A.
b[7] = 1 in array A.
  • 解题:
// 算法写在一个类里
class Solution {
    
    
public:
    ListNode* reverseBetween(ListNode* headA, ListNode* headB) {
    
    
        set<ListNode*> node_set;
        while (headA)
        {
    
    
            node_set.insert(headA);
            headA = headA->next;
        }
        while (headB)
        {
    
    
            if (node_set.find(headB) != node_set.end())
                return headB;
            headB = headB->next;
        }
        return NULL;
    }
    
};

方法2 对齐链表找相交点:

先对齐两条链表,使其同时出发能同时到达交点,(即让长的那条链表的出发点后移到与短的链表头出发点对齐),空间复杂度O(1)

// 遍历链表获得链表长度
int get_list_len(ListNode* head) {
    
    
    int len = 0;
    while (head)
    {
    
    
        len++;
        head = head->next;
    }
    return len;
}
// 使长链表定位到对齐位置
ListNode* forward_long_list(int longL, int shortL, ListNode* head) {
    
    
    int delta = longL - shortL;
    while (head && delta)
    {
    
    
        head = head->next;
        delta--;
    }
    return head;
}

// 算法写在一个类里
class Solution {
    
    
public:
    ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
    
    
        int lenA = get_list_len(headA);
        int lenB = get_list_len(headB);
        if (lenA>lenB)
        {
    
    
            headA = forward_long_list(lenA, lenB, headA);
        }
        else
        {
    
    
            headB = forward_long_list(lenB, lenA, headB);
        }
        while (headA&&headB)
        {
    
    
            if (headA == headB) {
    
    
                return headA;
            }
            headA = headA->next;
            headB = headB->next;
        }
        return NULL;
    }
    
};


// 以下为测试
int main() {
    
    
    // c1结点为两链表相交的结点
    ListNode a1(1);
    ListNode a2(2);
    ListNode b1(3);
    ListNode b2(4);
    ListNode b3(5);
    ListNode c1(6);
    ListNode c2(7);
    ListNode c3(8);
    a1.next = &a2;
    a2.next = &c1;
    c1.next = &c2;
    c2.next = &c3;
    b1.next = &b2;
    b2.next = &b3;
    b3.next = &c1;
    Solution solve;
    ListNode* result = solve.getIntersectionNode(&a1, &b1);
    cout << "交点为:" << result->val;
    return 0;
}

结果:

交点为:6

ps: 小象学院教程 https://www.bilibili.com/video/BV1GW411Q77S?t=7029&p=2 的笔记
LeetCode题号: 160

猜你喜欢

转载自blog.csdn.net/weixin_44427114/article/details/107792223