题目地址
编写一个程序,找到两个单链表相交的起始节点。
首先是常规解法:
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
Set<ListNode> set = new HashSet<>();
while (headA!= null || headB != null){
if (headA != null){
if (set.contains(headA)){
return headA;
}
set.add(headA);
headA = headA.next;
}
if (headB != null){
if (set.contains(headB)){
return headB;
}
set.add(headB);
headB = headB.next;
}
}
return null;
}
利用Set的特性,只要这个节点出现过就返回这个节点,即为交集。
第二种就是最浪漫的解法了:
如果两个链表有交集,那么a + c + b + c = b + c + a + c,速度一致、走过的路程一致,那么肯定会有一段交集是肩并肩一起走下去的,此时a.next = b.next,如果不相交 a + b = b + a,你走你的阳关道,我过我的独木桥,虽然走过的路相同,但永远没有交集。
public class Solution {
public ListNode getIntersectionNode(ListNode a, ListNode b) {
if (a == null || b == null){
return null;
}
ListNode aHead = a;
ListNode bHead = b;
while (a != b) {
//如果不相交,肯定同时到达“终点” 下一节点为null,跳出循环
if (a.next == null && b.next == null){
return null;
}
a = a.next == null ? bHead : a.next;
b = b.next == null ? aHead : b.next;
}
return a;
}
}