LeetCode160. 相交链表

94 篇文章 0 订阅
94 篇文章 6 订阅

编写一个程序,找到两个单链表相交的起始节点。

 

例如,下面的两个链表

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

在节点 c1 开始相交。

题目分析:首先求出链表A和链表B的长度,然后看长链表比短链表长几格,那么长链表的头结点就往后走几格,最后两个链表一起开始往后走,相遇的第一个节点就是起始节点。如果两个链表不相交的话,那么相遇的第一个节点必然是空节点。

代码展示:
 

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        int lenA = 0,lenB = 0;
        ListNode *tempA = headA;
        ListNode *tempB = headB;
        while(tempA!=NULL){
            tempA = tempA->next;
            lenA += 1;
        }
        while(tempB!=NULL){
            tempB = tempB->next;
            lenB += 1;
        }
        tempA = headA;
        tempB = headB;
        while(lenA>lenB){
            tempA = tempA->next;
            lenA -= 1;
        }
        while(lenB>lenA){
            tempB = tempB->next;
            lenB -= 1;
        }
        while(tempA!=tempB){
            tempA = tempA->next;
            tempB = tempB->next;
        }
        return tempA;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值