intersection-of-two-linked-lists

This commit is contained in:
Gleb Koval 2022-06-06 19:51:38 +01:00
parent 1a9d996416
commit 70fa350da8
Signed by: cyclane
GPG Key ID: 15E168A8B332382C
2 changed files with 72 additions and 0 deletions

View File

@ -0,0 +1,29 @@
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
}

View File

@ -0,0 +1,43 @@
package main
type ListNode struct {
Val int
Next *ListNode
}
// O(n + m) time and O(1) memory solution
// Gets the length of each list, then
// lines them up and searches for equal
// nodes.
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func getIntersectionNode(headA, headB *ListNode) *ListNode {
len1, len2 := getLen(headA), getLen(headB)
diff := len1 - len2
for diff > 0 {
headA = headA.Next
diff--
}
for diff < 0 {
headB = headB.Next
diff++
}
for headA != headB {
headA = headA.Next
headB = headB.Next
}
return headA
}
func getLen(head *ListNode) int {
len := 0
for current := head; current != nil; current = current.Next {
len++
}
return len
}