相交链表,菜bird考研记录

相交链表对应力扣160题。因为c++语法还在学习中,还没有学到哈希表,看题解是用哈希表写的,等后续学了哈希表再回来重新写过用哈希表的方法。我这里直接用的比较容易想到的,计算链表长度差,然后长短链表对齐,相交节点相同就行,写的比较冗余。

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        //计算两个链表的各自长度
        int count_A=0,count_B=0;
        ListNode *tempA=headA;
        ListNode *tempB=headB;
        while(tempA){
            count_A++;
            tempA=tempA->next;
        }
        tempA=headA;
        while(tempB){
            count_B++;
            tempB=tempB->next;
        }
        tempB=headB;
        //计算两个链表的长度差,相交节点以后一定一样长,移动长链表对齐于短链表
        int gas;
        if(count_A>=count_B){
            gas=count_A-count_B;
            while(gas>0){
                tempA=tempA->next;
                gas--;
            }
        }
        else{
            gas=count_B-count_A;
            while(gas>0){
                tempB=tempB->next;
                gas--;
            }
        }
        //进行遍历判断相同节点
        while(tempB){
        if(tempB == tempA) return tempA;
        else{
            tempA=tempA->next;
            tempB=tempB->next;
        }
        }
        return NULL;
    }
};

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值