Skip to content

Commit 11aa524

Browse files
committed
160 finish
1 parent 1c54331 commit 11aa524

File tree

1 file changed

+14
-9
lines changed

1 file changed

+14
-9
lines changed

Algorithms/0160.intersection-of-two-linked-lists/intersection-of-two-linked-lists.go

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,21 @@ import "github.com/aQuaYi/LeetCode-in-Go/kit"
66
type ListNode = kit.ListNode
77

88
func getIntersectionNode(headA, headB *ListNode) *ListNode {
9-
hasSeen := make(map[*ListNode]bool, 128)
10-
for headA != nil {
11-
hasSeen[headA] = true
12-
headA = headA.Next
13-
}
14-
for headB != nil {
15-
if hasSeen[headB] {
16-
return headB
9+
a, b := headA, headB
10+
hasLinkedToB, hasLinkedToA := false, false
11+
for a != nil && b != nil {
12+
if a == b {
13+
return b
14+
}
15+
a, b = a.Next, b.Next
16+
if a == nil && !hasLinkedToB {
17+
hasLinkedToB = true
18+
a = headB
19+
}
20+
if b == nil && !hasLinkedToA {
21+
hasLinkedToA = true
22+
b = headA
1723
}
18-
headB = headB.Next
1924
}
2025
return nil
2126
}

0 commit comments

Comments
 (0)