编写一个程序,找到两个单链表相交的起始节点。
如下面的两个链表:
输入: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 个节点。
输入:intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
输出:Reference of the node with value = 2
输入解释:相交节点的值为 2 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [0,9,1,2,4],链表 B 为 [3,2,4]。在 A 中,相交节点前有 3 个节点;在 B 中,相交节点前有 1 个节点。
第一种
利用 HashSet 直接存储一个A链表元素,把B中每个元素进行比较,包含的第一个则为相交点。 不符合空间要求
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
HashSet <ListNode> set = new HashSet<ListNode>();
ListNode A = headA;
ListNode B = headB;
while(A != null) {
set.add(A);
A = A.next;
}
while(B != null) {
if(set.contains(B)) {
return B;
}
B = B.next;
}
return null;
}
}
第二种
从图可以看出,如果 A.B长度一样的话,每个都走一个步,直接比较就可以找出。
故先遍历,A B 长度。 找出长度之差。
将较长的链表遍历到与另一个等长的节点, 就可以直接比较。
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode A = headA;
ListNode B = headB;
int numa = 0;
int numb = 0;
while(A != null) { //记录A长度
numa++;
A = A.next;
}
while(B != null) {//记录B 长度
numb++;
B = B.next;
}
A = headA;
B = headB;
if(numa > numb) { A比较长则将A遍历到与B齐长的节点
int n = numa-numb;
while(n > 0) {
A = A.next;
n--;
}
}else {
int n = numb-numa;
while(n > 0) {
B = B.next;
n--;
}
}
while(A != null) { 开始比较
if(A == B) return A;
A = A.next;
B = B.next;
}
return null;
}
}
第三种,利用环形链表,查找第一个重合点思想。
将一个链尾部与首相连,就可以按照环形链表解法解答。