相交链表 --java记录

编写一个程序,找到两个单链表相交的起始节点。

如下面的两个链表:
在这里插入图片描述
输入: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;
    }
}

第三种,利用环形链表,查找第一个重合点思想。
将一个链尾部与首相连,就可以按照环形链表解法解答。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值