LeetCode刷题日记 160.相交链表

LeetCode刷题日记 160.相交链表

题目描述:
编写一个程序,找到两个单链表相交的起始节点。
题目来源:https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
解法1:双指针
当指针跑完一个链表时,就去跑另一个链表,另一个指针也如此。如果两个链表相交的话,这两个指针总能相遇

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA ==null || headB == `在这里插入代码片`null) return null;
        ListNode pa = headA;
        ListNode pb = headB;
        while(pa! = pb){
           if(pa==null)  pa = headB;
           else pa = pa.next;
           if(pb==null)  pb = headA;
           else pb = pb.next;
        }
        return pa;
    }
}

解法2:哈希法,将一个链表的各个节点地址都存入哈希表中,在与另一个链表的结点地址比较


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

你可能感兴趣的:(LeetCode)