图解leetcode160.相交链表

1.题目描述:

给你两个单链表的头节点headA和headB,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回null。此题需要注意两点:头节点为链表的第一个节点而非虚拟节点;相交的节点不是指val值相同,而是内存中地址值指向相同的节点。(示例1中A链表两个4非相同节点因为next所指向不同)

 2.暴力解法:

在遍历A链表的同时,遍历B链表,判断是否存在指向同一个地址值的节点,存在则输出该节点,不存在则返回null。时间复杂度O(m * n),代码较简单如下:

/**
 * 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) {
        ListNode tempA = headA;
        ListNode tempB;
        while(tempA != null){
            tempB = headB;//重置tempB
            while(tempB != null){
                if(tempA == tempB){
                    return tempA;
                }else{
                    tempB = tempB.next;
                }
            }
            tempA = tempA.next;
        }
        return null;
    }
}

3.使用哈希集合HashSet:

遍历A链表,将其节点添加到HashSet(无序不重复)集合中,随后遍历B链表判断是否在集合中即可,时间复杂度O(m + n),空间复杂度O(m),代码较简单如下:

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

4.双指针解法:

同时遍历A链表和B链表,A链表遍历完后从B头节点继续遍历,B链表遍历完后从A头节点继续遍历,直到碰到相同节点循环结束,时间复杂度为O(m + n),但无需在内存中开辟集合空间,空间复杂度为O(1)。图解及代码如下:

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值