力扣面试题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;
    }
};
相关推荐
纪元A梦21 小时前
贪心算法应用:K-Means++初始化详解
算法·贪心算法·kmeans
_不会dp不改名_1 天前
leetcode_21 合并两个有序链表
算法·leetcode·链表
mark-puls1 天前
C语言打印爱心
c语言·开发语言·算法
Python技术极客1 天前
将 Python 应用打包成 exe 软件,仅需一行代码搞定!
算法
吃着火锅x唱着歌1 天前
LeetCode 3302.字典序最小的合法序列
leetcode
睡不醒的kun1 天前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌1 天前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
我星期八休息1 天前
深入理解跳表(Skip List):原理、实现与应用
开发语言·数据结构·人工智能·python·算法·list
lingran__1 天前
速通ACM省铜第四天 赋源码(G-C-D, Unlucky!)
c++·算法
haogexiaole1 天前
贪心算法python
算法·贪心算法