力扣面试题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;
    }
};
相关推荐
橙汁味的风23 分钟前
2EM算法详解
人工智能·算法·机器学习
维构lbs智能定位30 分钟前
北斗卫星导航定位从核心框架到定位流程详解(一)
算法·北斗卫星导航定位系统
byzh_rc32 分钟前
[算法设计与分析-从入门到入土] 动态规划
算法·动态规划
Halo_tjn35 分钟前
Java List集合知识点
java·开发语言·windows·算法·list
云飞云共享云桌面1 小时前
河北某机器人工厂8个研发设计共享一台SolidWorks云主机
运维·服务器·网络·数据库·算法·性能优化·机器人
元亓亓亓2 小时前
LeetCode热题100--152. 乘积最大子数组--中等
算法·leetcode·职场和发展
执笔论英雄2 小时前
【RL】Slime训练流程
算法
梭七y2 小时前
【力扣hot100题】(103)移动零
数据结构·算法·leetcode
weixin_413063213 小时前
测试《A Simple Algorithm for Fitting a Gaussian Function》拟合
python·算法
MarkHD3 小时前
智能体在车联网中的应用:第31天 基于RLlib的多智能体PPO实战:MAPPO算法解决simple_spread合作任务
算法