• 力扣:链表相交


    问题:给定两个(单向)链表,判定它们是否相交并返回交点。请注意相交的定义基于节点的引用,而不是基于节点的值。换句话说,如果一个链表的第k个节点与另一个链表的第j个节点是同一节点(引用完全相同),则这两个链表相交。

    在此题中,我们使用一个新的链表list存储headA,然后将B的引用和list的引用对比,如果存在,则返回引用节点,否则返回null。

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
            if (headA == null || headB == null) {
                return null;
            }
    
            List<ListNode> list = new LinkedList<>();
            ListNode curA = headA;
            while (curA != null) {
                list.add(curA);
                curA = curA.next;
            }
            ListNode curB = headB;
            while (curB != null) {
                if (list.contains(curB)) {
                    return curB;
                }
                curB = curB.next;
            }
            return null;
        }
    

    注意:第二种思路 采用双指针法。
    一针指向headA,一针指向headB。若相遇则返回,否则返回null。

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
            if(headA == null || headB == null)  return null;
    
            ListNode curA = headA,curB = headB;
            
            // 判断条件为,curA==null而curB!=null,反之亦然
            while(curA != curB){
                curA = curA == null ? headB : curA.next;
                curB = curB == null ? headA : curB.next;
            }
    
            return curA;
        }
    
  • 相关阅读:
    Linux 切换用户
    Java之.jdk安装-Linux
    Java之.jdk安装-Windows
    java注解生成xml和包含CDATA问题
    Spring学习—生成图片验证码
    java学习——java按值传递和按址传递
    温水中被煮熟的程序员-人生的思考
    mysql操作sql的小技巧
    java的classLoader分析与jettty的WebAppClassLoader
    深入Spring:自定义事务管理
  • 原文地址:https://www.cnblogs.com/njuptzheng/p/12789622.html
Copyright © 2020-2023  润新知