leetcode 160. Intersection of Two Linked Lists

本文介绍了一种寻找两个单链表交汇节点的算法。通过从两不同起点同时遍历,遇空指针则转向另一链表头部,最终同步抵达交点。此方法需O(n)时间复杂度及O(1)空间复杂度。

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

原题:

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


For example, the following two linked lists:

A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3

begin to intersect at node c1.


Notes:

  • If the two linked lists have no intersection at all, return null.
  • The linked lists must retain their original structure after the function returns.
  • You may assume there are no cycles anywhere in the entire linked structure.
  • Your code should preferably run in O(n) time and use only O(1) memory.

这个题目其实有些歧义的,因为这个判断的点不在于address,而是node。这相当于当作两个链表来做而不是真正意义上的交叉。

很简单,因为地址不一样。。。

但是这个东西的算法还是很巧妙,很不幸的是,我本来想用val做路标的,就算不行,实际上自己应用的时候是可以设计数据结构做路标就好。

但是这个不行。。。

所以看了答案,答案比较巧妙。

就是一个从a出发,一个从b出发,遇到NULL就换另一个链表头。原理是两个链表叠加,到达交叉点的时间一定是一样的。

代码如下:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
    struct ListNode* pA;
    struct ListNode* pB;
    pA=headA;
    pB=headB;
    if(pA==NULL||pB==NULL)
        return NULL;
    while(true)
    {
        if(pA==NULL&&pB==NULL)
            return NULL;
        if(pA==NULL)
        {
            pA=headB;
        }
        if(pB==NULL)
        {
            pB=headA;
        }
        if(pA->val==pB->val)
        {
            break;
        }
        pA=pA->next;
        pB=pB->next;
    }
    return pA;
}
如果是真正的链表,我觉得做一次路标更省事。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值