力扣面试题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;
    }
};
相关推荐
Swift社区3 分钟前
LeetCode 460 - LFU 缓存
算法·leetcode·缓存
程芯带你刷C语言简单算法题28 分钟前
Day39~实现一个算法确定将一个二进制整数翻转为另一个二进制整数,需要翻转的位数
c语言·开发语言·学习·算法·c
zcbdandan34 分钟前
JNA内存对齐导致的结构体数组传输错误
数据结构·算法
dundunmm42 分钟前
【每天一个知识点】YOLO算法
算法·yolo·目标检测
lihihi1 小时前
P5182 棋盘覆盖
算法·图论
白云千载尽1 小时前
LLaMA-Factory 入门(一):Ubuntu20 下大模型微调与部署
人工智能·算法·大模型·微调·llama
yugi9878381 小时前
基于Takens嵌入定理和多种优化算法的混沌序列相空间重构MATLAB实现
算法·matlab·重构
Yuer20251 小时前
为什么要用rust做算子执行引擎
人工智能·算法·数据挖掘·rust
持梦远方1 小时前
持梦行文本编辑器(cmyfEdit):架构设计与十大核心功能实现详解
开发语言·数据结构·c++·算法·microsoft·visual studio
im_AMBER2 小时前
Leetcode 90 最佳观光组合
数据结构·c++·笔记·学习·算法·leetcode