leetcode之Intersection of Two Linked Lists

本文介绍了一种寻找两个单链表交汇开始节点的方法。通过计算两链表长度差并同步移动指针,最终找到第一个相同节点即为交点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

Write a program to find the node at which the intersection of two singly linked lists begins.

解答:
作为曾经大二暑假去面度娘实习被问的题目之一,看到之后格外温馨(然而面度娘的时候还并没有刷过一道leetcode。。。
其实把图画出来就会很简单,如果两个链表由交点,那么最终一定是链表终点是一样的,假设一个长Len1,另一个是Len2,如果Len1 > Len2,那么在L1的前Len1 - Len2个节点中一定不会有交点,只需要拿L1的后Len2个和L2比较即可,用两个指针就可以轻易比较
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    int linkLen(ListNode *head)
    {
        int cnt = 0;
        while(head)
        {
            head = head->next;
            cnt++;
        }
        return cnt;
    }
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        int lenA = linkLen(headA);
        int lenB = linkLen(headB);
        int proceed = abs(lenA - lenB);
        if(lenA > lenB)
        {
            for(int i = 0;i < proceed;++i)
                headA = headA->next;
        }
        else
        {
            for(int i = 0;i < proceed;++i)
                headB = headB->next;
        }
        while(headA && headB)
        {
            if(headA == headB)
                return headA;
            headA = headA->next;
            headB = headB->next;
        }
        return NULL;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值