我的代码-哈希表屡用不爽
import java.util.HashMap;
/*
* @lc app=leetcode.cn id=160 lang=java
*
* [160] 相交链表
*/
// Definition for singly-linked list.
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) return null;
if (headA == headB) return headA;
HashMap<ListNode, Integer> hashMap = new HashMap<ListNode, Integer>();
hashMap.put(headA, headA.val);
hashMap.put(headB, headB.val);
ListNode nextA = headA.next;
ListNode nextB = headB.next;
while (nextA != null && nextB != null) {
if (!hashMap.containsKey(nextA)) {
hashMap.put(nextA, nextA.val);
} else {
return nextA;
}
if (!hashMap.containsKey(nextB)) {
hashMap.put(nextB, nextB.val);
} else {
return nextB;
}
nextA = nextA.next;
nextB = nextB.next;
}
while (nextA != null) {
if (!hashMap.containsKey(nextA)) {
hashMap.put(nextA, nextA.val);
} else {
return nextA;
}
nextA = nextA.next;
}
while (nextB != null) {
if (!hashMap.containsKey(nextB)) {
hashMap.put(nextB, nextB.val);
} else {
return nextB;
}
nextB = nextB.next;
}
return null;
}
}
大佬的代码-巧妙解法
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
/**
定义两个指针, 第一轮让两个到达末尾的节点指向另一个链表的头部, 最后如果相遇则为交点(在第一轮移动中恰好抹除了长度差)
两个指针等于移动了相同的距离, 有交点就返回, 无交点就是各走了两条指针的长度
**/
if(headA == null || headB == null) return null;
ListNode pA = headA, pB = headB;
// 在这里第一轮体现在pA和pB第一次到达尾部会移向另一链表的表头, 而第二轮体现在如果pA或pB相交就返回交点, 不相交最后就是null==null
while(pA != pB) {
pA = pA == null ? headB : pA.next;
pB = pB == null ? headA : pB.next;
}
return pA;
}
}