Created
July 23, 2020 20:41
-
-
Save mcfearsome/44022e4dbc4b2fc8806432fcf1e54e50 to your computer and use it in GitHub Desktop.
Things got out of hand messing with a simple Leet Code problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type ListNode struct { | |
Val int | |
Next *ListNode | |
} | |
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { | |
pc := make(chan int, 4) | |
var ( | |
wg sync.WaitGroup | |
root *ListNode | |
) | |
// producer | |
// Send the Link List values to the channel alternating | |
wg.Add(1) | |
go func(wg *sync.WaitGroup) { | |
defer wg.Done() | |
for l1 != nil || l2 != nil { | |
if l1 != nil { | |
pc <- l1.Val | |
l1 = l1.Next | |
} else { | |
pc <- 0 | |
} | |
if l2 != nil { | |
pc <- l2.Val | |
l2 = l2.Next | |
} else { | |
pc <- 0 | |
} | |
} | |
close(pc) | |
}(&wg) | |
// Consumer | |
wg.Add(1) | |
go func(wg *sync.WaitGroup) { | |
defer wg.Done() | |
var ( | |
a, b, sum, carry int | |
ok bool | |
current *ListNode | |
) | |
for { | |
// recieve from producer in pairs | |
a = <-pc | |
b, ok = <-pc | |
if !ok { | |
if carry > 0 { | |
current.Next = &ListNode{Val: carry} | |
} | |
break | |
} | |
// Do the maths | |
sum = a + b + carry | |
carry = 0 | |
if sum > 9 { | |
carry = 1 | |
sum -= 10 | |
} | |
if root == nil { | |
root = &ListNode{} | |
current = root | |
} else { | |
current.Next = &ListNode{} | |
current = current.Next | |
} | |
current.Val = sum | |
} | |
}(&wg) | |
wg.Wait() | |
return root | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment