CodeTop014 相交链表

相交链表
给你两个单链表的头节点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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值