一.问题描述
-
编写一个程序,找到两个单链表相交的起始节点。
-
输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
-
输出:Reference of the node with value = 8
-
输入解释:相交节点的值为 8 (注意,如果两个链表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。
二.示例代码
public static void main(String[] args) {
ListNode listNode = new ListNode(4);
ListNode listNode1 = new ListNode(1);
ListNode listNode2 = new ListNode(8);
ListNode listNode3 = new ListNode(4);
ListNode listNode4 = new ListNode(5);
listNode3.next = listNode4;
listNode2.next = listNode3;
listNode1.next = listNode2;
listNode.next = listNode1;
ListNode listNode5 = new ListNode(5);
ListNode listNode6 = new ListNode(0);
ListNode listNode7 = new ListNode(1);
listNode5.next = listNode6;
listNode6.next = listNode7;
listNode7.next = listNode2;
ListNode result = intersectedList2(listNode, listNode5);
System.out.println(listNode);
System.out.println(listNode5);
System.out.println(result);
}
private static ListNode intersectedList(ListNode headA, ListNode headB) {
ListNode p = headA;
ListNode q = headB;
Set<ListNode> set = new HashSet<>();
while (p != null) {
set.add(p);
p = p.next;
}
while (q != null) {
if (set.contains(q)) {
return q;
}
q = q.next;
}
return null;
}
public static ListNode intersectedList2(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
ListNode head1 = headA;
ListNode head2 = headB;
while (head1 != head2) {
if (head1 != null) {
head1 = head1.next;
} else {
head1 = headB;
}
if (head2 != null) {
head2 = head2.next;
} else {
head2 = headA;
}
}
return head1;
}