力扣面试题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;
    }
};
相关推荐
随意起个昵称18 小时前
区间dp-基础题目1(石子合并)
算法·动态规划
吞下星星的少年·-·18 小时前
线段树模板
算法
段一凡-华北理工大学19 小时前
2026 高炉炼铁智能化技术全景与演进路径~系列文章11:演进路径与行业未来
大数据·网络·人工智能·算法·工业智能体·高炉炼铁智能化
叶小鸡19 小时前
小鸡玩算法-力扣HOT100-多维动态规划
算法·leetcode·动态规划
星马梦缘19 小时前
aaaaa
数据结构·c++·算法
菜菜的顾清寒20 小时前
力扣HOT100(42)链表-随机链表的复制
算法·leetcode·链表
lqqjuly20 小时前
模型剪枝与稀疏化:理论、算法与可运行实现
人工智能·算法·剪枝
逻辑君20 小时前
Foresight研究报告【20260011】
人工智能·线性代数·算法·矩阵
珊瑚里的鱼20 小时前
【动态规划】不同路径Ⅱ
算法·动态规划
适应规律21 小时前
【无标题】
人工智能·python·算法