相交链表的交点

 

https://leetcode.cn/problems/intersection-of-two-linked-lists/solution/xiang-jiao-lian-biao-by-leetcode-solutio-a8jn/

 

 

 

 

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func getIntersectionNode(headA, headB *ListNode) *ListNode {
    if headA==nil||headB==nil{
        return nil
    }
    ha:=headA;hb:=headB
    for ha!=hb{
        if ha==nil{
            ha=headB
        }else{
            ha=ha.Next
        }

        if hb==nil{
            hb=headA
        }else{
            hb=hb.Next
        }
    }
    return ha
}

//用hash集合标记存在的链表
func getList(headA, headB *ListNode) *ListNode {
    if headA==nil||headB==nil{
        return nil
    }
    mp:=make(map[*ListNode]bool,0)
    for headA!=nil{
        mp[headA]=true
        headA=headA.Next
    }

    for headB!=nil{
        if mp[headB]{
            return headB
        }
        headB=headB.Next
    }
    return nil
}

 

posted @ 2022-07-01 12:07  知道了呀~  阅读(55)  评论(0编辑  收藏  举报