LeetCode 160. 相交链表

题目链接:

力扣icon-default.png?t=M276https://leetcode-cn.com/problems/intersection-of-two-linked-lists/

 

【方法一】用哈希表存其中一条链的节点,在遍历第二条链的时候检查是否在哈希表中即可。

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        Set<ListNode> set = new HashSet<>();
        while(headA != null){
            set.add(headA);
            headA = headA.next;
        }
        while(headB != null){
            if(set.contains(headB)) return headB;
            headB = headB.next;
        }
        return null;
    }
}

【方法二】让两个链表头指针p、q一起跑,剩下没跑完的就是多出来的长度,让长的再跑这些长度,使二者对其,然后继续同时跑。

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode p = headA, q = headB, r;
        while(p != null && q!= null){
            p = p.next;
            q = q.next;
        }
        if(p != null) {
            r = headA;
            while(p != null){
                p = p.next;
                r = r.next;
            }
            q = headB;
            while(r != null){
                if(r == q) return r;
                r = r.next;
                q = q.next;
            }
        }else if(q != null){
            r = headB;
            while(q != null){
                r = r.next;
                q = q.next;
            }
            p = headA;
            while(r != null){
                if(r == p) return r;
                r = r.next;
                p = p.next;
            }
        }else{
            p = headA;
            q = headB;
            while(p != null){
                if(p == q) return p;
                p = p.next;
                q = q.next;
            }
        }
        return null;
    }
}

【方法三】这个方法真的特别好! “走到尽头见不到你,于是走过你来时的路,等到相遇时才发现,你也走过我来时的路。”

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode p = headA, q = headB;
        while(p != q){
            p = p == null ? headB : p.next;
            q = q == null ? headA : q.next;
        }
        return p;
    }
}

 

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值