[LeetCode 160]相交链表

[LeetCode 160]C++实现相交链表

示例:
输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
输出:Reference of the node with value = 8
输入解释:相交节点的值为 8 (注意,如果两个链表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。

来源:力扣(LeetCode 160)
链接:https://leetcode-cn.com/problems/intersection-of-two-linked-lists

方法1、使用STL中set

class Solution {
public:
    ListNode* getIntersectionNode(ListNode *headA, ListNode *headB) {
        set<ListNode* > s;
        while(headA){
            s.insert(headA);
            headA=headA->next;
        }
        
        while(headB){             
            if(s.find(headB)==s.end()){
                s.insert(headB);
                headB=headB->next;
            }
            else{
                return headB;
            }   
        }
        return NULL;
    }
};

方法2、减小长链表至二者长度相等,遍历到相等

class Solution {
public:
    int getSize(ListNode* head){
        int count=0;
        while(head!=NULL){
            count++;
            head=head->next;
        }
        return count;
    }

    ListNode* removeLonger(ListNode* head,int long_len,int short_len){
        int length=long_len-short_len;
        while(head&&length--){
            head=head->next;
        }
        return head;
    }
    ListNode* getIntersectionNode(ListNode *headA, ListNode *headB) {
        int A_Size=getSize(headA);
        int B_Size=getSize(headB);
        if(A_Size>B_Size){
            headA=removeLonger(headA,A_Size,B_Size);
        } 
        else{
            headB=removeLonger(headB,B_Size,A_Size);
        }
        while(headA!=headB){
                headA=headA->next;
                headB=headB->next;
        }
        if(headA!=NULL)
            return headA;
        else
            return NULL;

    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值