力扣面试题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;
    }
};
相关推荐
程序员莫小特2 小时前
老题新解|大整数加法
数据结构·c++·算法
过往入尘土3 小时前
服务端与客户端的简单链接
人工智能·python·算法·pycharm·大模型
zycoder.3 小时前
力扣面试经典150题day1第一题(lc88),第二题(lc27)
算法·leetcode·面试
Dream it possible!3 小时前
LeetCode 面试经典 150_哈希表_存在重复元素 II(46_219_C++_简单)
leetcode·面试·散列表
蒙奇D索大3 小时前
【数据结构】考研数据结构核心考点:二叉排序树(BST)全方位详解与代码实现
数据结构·笔记·学习·考研·算法·改行学it
智驱力人工智能4 小时前
工厂抽烟检测系统 智能化安全管控新方案 加油站吸烟检测技术 吸烟行为智能监测
人工智能·算法·安全·边缘计算·抽烟检测算法·工厂抽烟检测系统·吸烟监测
学学学无无止境4 小时前
组合两个表-力扣
leetcode
程序员爱钓鱼4 小时前
Go语言实战案例——进阶与部署篇:编写Makefile自动构建Go项目
后端·算法·go
_Power_Y5 小时前
Java面试常用算法api速刷
java·算法·面试
艾醒(AiXing-w)5 小时前
大模型面试题剖析:模型微调中冷启动与热启动的概念、阶段与实例解析
人工智能·深度学习·算法·语言模型·自然语言处理