Leetcode hot 100 5.相交链表

1.题目

160. 相交链表

给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。

图示两个链表在节点 c1 开始相交

题目数据 保证 整个链式结构中不存在环。

注意,函数返回结果后,链表必须 保持其原始结构 

2.答案

/**

 * Definition for singly-linked list.

 * struct ListNode {

 *     int val;

 *     ListNode *next;

 *     ListNode(int x) : val(x), next(NULL) {}

 * };

 */

class Solution {

public:

    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {

        unordered_set <ListNode*> node;

        ListNode *temp=headA;

        while(temp!=nullptr){

            node.insert(temp);

            temp=temp->next;

        }

        temp=headB;

         while (temp != nullptr) {

            if (node.count(temp)) {

 count() 的作用
  • count() 是集合的方法,用于检查某个元素是否存在于集合中。

  • 返回值:

    • 1:如果元素存在于集合中。

    • 0:如果元素不存在于集合中。

3. node.count(temp) 的含义
  • 检查 temp 是否存在于集合 node 中。

  • 如果存在,返回 1;否则返回 0

                return temp;

            }

            temp = temp->next;

        }


 

        return nullptr;

    }

};

我发现hot 都要用哈希表啊?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农珊珊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值