相交链表-力扣

题目链接:https://leetcode-cn.com/problems/intersection-of-two-linked-lists/返回两个链表交点的指针。
此题题目中给的输入样例并不是很清楚,实际上只输入了两只头指针。

思路:

判断两个链表长度,然后求差=times.
让指向较长链表的指针先走times步,然后两个指针同时向前走,当指向的地址相同的时候返回。

典型的代码块:

1.判断链表长度:

    while (a){
        a = a->next;
        len_A++;
    }

2.让指针向前走time次

        while(times){
        times--;
        a = a->next;
        }

最终代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
    struct ListNode *a = headA;
    struct ListNode *b = headB;
    int len_A=0,len_B=0,times;

    while (a){
        a = a->next;
        len_A++;
    }
    while (b){
        b = b->next;
        len_B++;
    }
    a = headA;
    b = headB;
    if (len_A-len_B>0){
        times = len_A-len_B;
        while(times){
        times--;
        a = a->next;
        }
    }    
    if (len_A-len_B<0){
        times = len_B-len_A;
        while(times){
        times--;
        b = b->next;
        }
    }

    while(a && b){
        if(a==b) return a;
        else{
            a = a->next;
            b = b->next;
        }    
    }
    return NULL;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值