目录
题目描述:
给你两个单链表的头节点 head1
和 head2
,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null。
解法1.
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; this.next = null; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA==null || headB==null){
return null;
}
ListNode nestA = headA;
ListNode nestB = headB;
while(nestA != nestB){
nestA = nestA==null ? headA : nestA.next;
nestB = nestB==null ? headB : nestB.next;
}
return nestA;
}
解法2.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
public static Node getIntersectionNode(Node head1,Node head2){
if(head1==null || head2==null){
return null;
}
Node cur1 = head1;
Node cur2 = head2;
int n = 0;
while(cur1!=null){
n++;
cur1 = cur1.next;
}
while(cur2!=null){
n--;
cur2 = cur2.next;
}
if(cur1!=cur2){
return null;
}
cur1 = n > 0 ? head1 : head2;
cur2 = cur1 == head1 ? head2 : head1;
n = Math.abs(n);
while(n!=0){
n--;
cur1 = cur1.next;
}
while(cur1!=cur2){
cur1 = cur1.next;
cur2 = cur2.next;
}
return cur1;
}