力扣面试题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;
    }
};
相关推荐
QuZero21 分钟前
Guava Cache Deep Dive
java·后端·算法·guava
随意起个昵称28 分钟前
线性dp-LIS题目4(A Twisty Movement)
算法·动态规划
Felven38 分钟前
B. Fair Numbers
数据结构·算法
人道领域42 分钟前
【LeetCode刷题日记】93.复原IP地址
java·开发语言·算法·leetcode
jarreyer1 小时前
【算法记录1】模型训练问题
算法
Felven1 小时前
D. Friends and the Restaurant
算法
想吃火锅10051 小时前
【leetcode】165.比较版本号js
javascript·算法·leetcode
San813_LDD1 小时前
[量化]《浮点数比较的艺术:从内存布局到极致性能优化》
网络·算法
ysu_03141 小时前
leetcode数据结构与算法1~4
c语言·数据结构·学习·算法·leetcode
小欣加油1 小时前
leetcode2574 左右元素和的差值
数据结构·c++·算法·leetcode·职场和发展