leedcode160 相交链表。返回两个链表的相交的起始节点

public class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
        next = null;
    }
}

方法一:哈希集合

import java.util.HashSet;
import java.util.Set;

//哈希集合
public class Solution1 {
    public ListNode getIntersectionNode(ListNode headA,ListNode headB){
        //使用哈希集合储存一个链表的结点
        //遍历第二条链表,用第二条链表的每个结点去哈希集合中找
        Set<ListNode> visited = new HashSet<>();
        ListNode temp = headA;
        while(temp != null){
            visited.add(temp);
            temp = temp.next;
        }
        temp = headB;
        while(temp != null){
            if(visited.contains(temp)){
                return temp;
            }
            temp = temp.next;
        }
        return null;
    }
}

方法二:双指针法

//双指针法
public class Solution2 {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        //定义两个指针分别指向两个链表的头结点,同时前进
        //当两个结点分别指向NULl时,则指向另外一个链表得头结点
        //当两个结点相等或者为空时,返回
        if(headA == null || headB == null){
            return null;
        }
        ListNode prev = headA;
        ListNode cur = headB;
        while(prev != cur){
            prev = prev == null ? headB : prev.next;
            cur = cur == null ? headA : cur.next;
        }
        return prev;
    }
}

猜你喜欢

转载自blog.csdn.net/crazy_tan/article/details/130712564