力扣面试题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;
    }
};
相关推荐
爱思德学术15 小时前
中国计算机学会(CCF)推荐学术会议-B(计算机体系结构/并行与分布计算/存储系统):SPAA 2026
算法
15 小时前
2.12矩阵问题,发牌,数字金字塔
线性代数·算法·矩阵
无聊的小坏坏15 小时前
一文讲通:二分查找的边界处理
数据结构·c++·算法
m0_5287490015 小时前
C语言错误处理宏两个比较重要的
java·linux·算法
TracyCoder12316 小时前
LeetCode Hot100(50/100)——153. 寻找旋转排序数组中的最小值
算法·leetcode·职场和发展
诸葛务农16 小时前
点云配准在人形机器人中的应用:ICP算法(2)
人工智能·算法·机器学习·机器人
摘星编程16 小时前
**解锁Agent智能体新纪元:自主协作、任务分解与人类意图对齐的终极指南**
算法
mmz120716 小时前
逆序对问题(c++)
c++·算法
化学在逃硬闯CS16 小时前
Leetcode110.平衡二叉树
数据结构·c++·算法·leetcode
谢铭轩16 小时前
题解:P8035 [COCI 2015/2016 #7] Otpor
c++·算法