Leetcode 160 Intersection of Two Linked Lists

题意

给定两个链表,找这两个链表第一个公共节点,如果没有返回nullptr

题目链接

https://leetcode.com/problems/intersection-of-two-linked-lists/description/

题解

两个指针分别从两个链表(记录为表A,表B)的表头出发,并且记录到表尾移动的步数,得到两个指针移动的步数之差 x x x。步数之差为正数,那么把表A的指针移动 x x x步,否则移动表B的指针 − x -x x步。然后两个指针移动到表尾,得到答案。

/**
 * 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 *p1 = headA;
        ListNode *p2 = headB;
        int cnt1 = 0;
        int cnt2 = 0;
        while(p1) {
            p1 = p1->next;
            cnt1++;
        }
        while(p2) {
            p2 = p2->next;
            cnt2++;
        }
        p1 = headA;
        p2 = headB;
        int cnt3 = abs(cnt1 - cnt2);
        if(cnt1 >= cnt2) {
            for(int i = 0; i < cnt3; i++) {
                p1 = p1->next;
            }
        } else {
            for(int i = 0; i < cnt3; i++) {
                p2 = p2->next;
            }            
        }
        while(p1 != p2 && p1 != nullptr) {
            p1 = p1->next;
            p2 = p2->next;
        }
        return p1 == nullptr ? nullptr : p1;
    }
};

算法复杂度: O ( m + n ) O(m+n) O(m+n) m m m n n n分别为两个表的长度
空间复杂度: O ( 1 ) O(1) O(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值