Skip to content

Instantly share code, notes, and snippets.

@BaReinhard
Created February 21, 2019 19:54
Show Gist options
  • Save BaReinhard/34d8a38e5adcc1aca5627490d04f9bca to your computer and use it in GitHub Desktop.
Save BaReinhard/34d8a38e5adcc1aca5627490d04f9bca to your computer and use it in GitHub Desktop.
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
// Check that l1 and l2 are not empty
if l1 == nil && l2 == nil{
fmt.Printf("2 Empty Nodes Found")
return nil
}else if l1 == nil{
return l2
}else if l2 == nil{
return l1
}
// assuming that each node can only hold a single digit integer
// set initial variables to use inside loop
carryOver := 0
returnNode:= &ListNode{}
currentReturnNode:= returnNode
fn:= l1
sn:= l2
fnEnded:= false
snEnded:= false
// golang version of while loop
for{
fv:= fn.Val
sv:= sn.Val
sum:= fv + sv + carryOver
if sum > 9{
carryOver = 1
}else {
carryOver = 0
}
currentReturnNode.Val = sum % 10
if fn.Next == nil{
fnEnded = true
fn = &ListNode{}
}else{
fn = fn.Next
}
if sn.Next == nil{
snEnded = true
sn = &ListNode{}
}else{
sn = sn.Next
}
if fnEnded && snEnded && carryOver == 0{
return returnNode
}else{
currentReturnNode.Next = &ListNode{}
currentReturnNode = currentReturnNode.Next
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment