力扣面试题02.07-链表相交

链表相交

题目链接

解题思路:

  1. 题目可以确定如果相交,那么相交的部分一定是在链表的结尾部分
  2. 第一步求得两条链表的长度
  3. 第二步长度做差,将长的那条链表与短的那条链表后部分对其
  4. 第三步遍历后面的部分,如果当前节点相等,直接返回,否则返回null
java 复制代码
/**
 * 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=0;
        int lenB=0;
        ListNode* curA = headA;
        ListNode* curB = headB;
        while (curA != NULL) {
            lenA++;
            curA = curA->next;
        }
        while (curB != NULL) {
            lenB++;
            curB = curB->next;
        }
        curA = headA;
        curB = headB;
        if (lenA > lenB) {
            int temp = lenA - lenB;
            while (temp--) {
                curA = curA->next;
            }
            while (curA != NULL) {
                if (curA == curB) {
                    return curA;
                }
                curA = curA->next;
                curB = curB->next;
            }
        }else{
            int temp = lenB - lenA;
            while (temp--) {
                curB = curB->next;
            }
            while (curB != NULL) {
                if (curA == curB) {
                    return curA;
                }
                curA = curA->next;
                curB = curB->next;
            }
        }

        return NULL;
    }
};
相关推荐
我爱Jack10 分钟前
时间与空间复杂度详解:算法效率的度量衡
java·开发语言·算法
DoraBigHead2 小时前
小哆啦解题记——映射的背叛
算法
Heartoxx2 小时前
c语言-指针与一维数组
c语言·开发语言·算法
孤狼warrior2 小时前
灰色预测模型
人工智能·python·算法·数学建模
京东云开发者2 小时前
京东零售基于国产芯片的AI引擎技术
算法
chao_7893 小时前
回溯题解——子集【LeetCode】二进制枚举法
开发语言·数据结构·python·算法·leetcode
十盒半价4 小时前
从递归到动态规划:手把手教你玩转算法三剑客
javascript·算法·trae
GEEK零零七4 小时前
Leetcode 1070. 产品销售分析 III
sql·算法·leetcode
凌肖战4 小时前
力扣网编程274题:H指数之普通解法(中等)
算法·leetcode
秋说4 小时前
【PTA数据结构 | C语言版】将数组中元素反转存放
c语言·数据结构·算法