leet-code/intersection-of-two-linked-.../sol.go

30 lines
620 B
Go
Raw Permalink Normal View History

2022-06-06 18:51:38 +00:00
package main
type ListNode struct {
Val int
Next *ListNode
}
// O(n+m) time and O(n) memory solution
// Only iterates over each list once, unlike
// the other solution which iterates twice.
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func getIntersectionNode(headA, headB *ListNode) *ListNode {
exists := map[*ListNode]bool{}
for current := headA; current != nil; current = current.Next {
exists[current] = true
}
for current := headB; current != nil; current = current.Next {
if exists[current] {
return current
}
}
return nil
}