题目链接:https://leetcode.cn/problems/intersection-of-two-linked-lists/description/?envType=study-plan-v2&envId=top-100-liked
哈希集合
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
//创建一个哈希集合
Set<ListNode> s = new HashSet<ListNode>();
//临时存储A
ListNode t = headA;
//遍历A
while(t != null){
//添加当前元素
s.add(t);
//指向下一个元素
t = t.next;
}
t = headB;
//遍历B
while(t != null){
//如果A中包含B,那就返回当前元素
if(s.contains(t)){
return t;
}
//指向下一个元素
t = t.next;
}
return null;
}
}
双指针
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode a = headA, b = headB;
//相等时为相交或都指向null
while(a != b){
a = a == null ? headB : a.next;
b = b == null ? headA : b.next;
}
return b;
}
}
还剩78题!