相交链表
给你两个单链表的头节点headA和headB,请你找出并返回两个单链表相交的起始节点.如果两个链表不存在相交节点,返回null
这题就是个简单题.没啥好说的
public class Solution014 {
public static void main(String[] args) {
ListNode c3 = new ListNode(8),
c2 = new ListNode(7,c3),
c1 = new ListNode(6,c2),
b3 = new ListNode(5,c1),
b2 = new ListNode(4,b3),
b1 = new ListNode(3,b2),
a2 = new ListNode(2,c1),
a1 = new ListNode(1,a2);
System.out.println(getIntersectionNode2(a1, b1).toString());
}
//HashSet(不建议)
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA==null || headB==null) return null;
HashSet<ListNode> set = new HashSet<>();
ListNode cur = headA;
while(cur!=null){
set.add(cur);
cur = cur.next;
}
cur = headB;
while (cur!=null){
if (set.contains(cur)){
return cur;
}
cur = cur.next;
}
return null;
}
//双指针(需要注意的是判断条件的时候是(pA==null ? headB : pA.next)而不是(pA.next==null ? headB : pA.next)) 这个要特别注意
public static ListNode getIntersectionNode2(ListNode headA, ListNode headB) {
if (headA==null || headB==null) return null;
ListNode pA = headA,pB = headB;
while (pA!=pB){
pA = (pA==null ? headB : pA.next);
pB = (pB==null ? headA : pB.next);
}
//最终要么同时指向相交的节点 要么同时指向null
return pA;
}
}