Loading

160-相交链表

一、暴力解法

二、哈希表思路

将A链表放入哈希表中,对B链表进行遍历,查询是否有元素存在哈希表中。

哈希表建立方法: set<ListNode*>hash;

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
12         set<ListNode*>hash;
13         while(headA)
14         {
15             hash.insert(headA);
16             headA=headA->next;
17         }
18         while(headB)
19         {
20             if(hash.find(headB)!=hash.end())
21             {
22                 return headB;
23             }
24             else
25             {
26                 headB=headB->next;
27             }
28         }
29         return NULL;
30 
31 
32         
33     }
34 };
View Code

 

知识点链接:https://blog.csdn.net/lady_killer9/article/details/79259378

posted @ 2020-03-04 12:20  是凉城吖  阅读(113)  评论(0编辑  收藏  举报