LeetCode刷题笔记——相交链表

2. 相交链表
  • 难度级别:简单

  • 题目类型:链表

  • 题目描述:

  • 解题思路:

  • 双指针法:

  • 开始时用临时指针tempA, tempB分别指向headA, headB;

  • 两个临时指针分别从两个链表的起点开始遍历:若其中一个指针到达链表尾部,两指针还没相遇,就将该指针指向另一个链表的头部,继续往下走;

  • 在遍历过程中,因为两个临时指针走的路程是一样的,因此,若两个链表相交,在相交的第一个结点相遇;否则两个结点会同时到达两个链表的尾部,返回结果就是null。

  • 时间复杂度:O(m+n)

  • 空间复杂度:O(1)

  • 哈希表法:

  • 将其中一个链表复制进一个哈希表中,这样用另一个链表与哈希表进行比较,如果哈希表中发现结点相同,该结点就是需要返回的结果;否则返回null。

  • 时间复杂度:O(m+n)

  • 空间复杂度:O(m)

  • 源代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        //双指针法
       /* if(headA == null || headB == null)
            return null;
        ListNode preA = headA;
        ListNode preB = headB;
        while(preA != preB)
        {
            preA = (preA == null) ? headB : preA.next;
            preB = (preB == null) ? headA : preB.next;
        }
        return preA;*/

        // 哈希表
        if(headA == null || headB == null)
            return null;
        Set<ListNode> copyA = new HashSet<ListNode>();
        ListNode tempA = headA, tempB = headB;
        while(tempA != null)
        {
            copyA.add(tempA);
            tempA = tempA.next;
        }
        while(tempB != null)
        {
            if(copyA.contains(tempB))
                return tempB;
            tempB = tempB.next;
        }
        return null;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值