/**
* 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> set = new HashSet<>();
ListNode pA = headA;
while (pA != null) {
set.add(pA);
pA = pA.next;
}
ListNode pB = headB;
while (pB != null) {
if (set.contains(pB)) return pB;
pB = pB.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) {
int lenA = getLen(headA);
int lenB = getLen(headB);
ListNode pA = headA;
ListNode pB = headB;
if (lenA > lenB) {
for (int i = 0; i < lenA - lenB; i++) {
pA = pA.next;
}
} else {
for (int i = 0; i < lenB - lenA; i++) {
pB = pB.next;
}
}
while (pA != pB) {
pA = pA.next;
pB = pB.next;
}
return pA;
}
public int getLen(ListNode head) {
int len = 0;
while (head != null) {
len++;
head = head.next;
}
return len;
}
}
方法三:双指针
/**
* 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) {
//存在链表为空时,一定不相交
if (headA == null || headB == null) return null;
ListNode pA = headA;
ListNode pB = headB;
while (pA != pB) {
pA = pA == null ? headB : pA.next;
pB = pB == null ? headA : pB.next;
}
//当指针 pA 和 pB 指向同一个节点或者都为 null 时,返回它们指向的节点或者null
return pA;
}
}
方法一:哈希表/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode getInt..