Skip to content

Instantly share code, notes, and snippets.

@r14152
Created August 14, 2021 11:33
Show Gist options
  • Select an option

  • Save r14152/db4e2173ac5ea8f7289a9bc1305e3d38 to your computer and use it in GitHub Desktop.

Select an option

Save r14152/db4e2173ac5ea8f7289a9bc1305e3d38 to your computer and use it in GitHub Desktop.
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func Push(lst *ListNode, x int) *ListNode{
temp := &ListNode{Val:x,Next:nil}
if lst == nil {
//fmt.Println("InsideLst")
lst = new(ListNode)
lst = temp
return lst
}
head := lst
for nil != head.Next {
//fmt.Println("ListDetails :", head.Val)
head = head.Next
}
head.Next = temp
return lst
}
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
var remain int
var lst *ListNode
for nil != l1 && nil !=l2 {
//fmt.Println(l1.Val , l2.Val)
sum := l1.Val + l2.Val + remain
remain = 0
if sum > 9 {
remain = sum/10
digit := sum%10
lst = Push(lst,digit)
}else{
lst = Push(lst,sum)
}
l1 = l1.Next
l2 = l2.Next
}
tempNode := new(ListNode)
if nil == l1 && nil == l2{
if remain != 0{
lst = Push(lst, remain)
}
return lst
}else if nil == l1 && nil != l2 {
tempNode = l2
} else if nil != l1 && nil == l2{
tempNode = l1
}
for nil != tempNode {
sum := tempNode.Val + remain
remain = 0
if sum > 9 {
remain = sum/10
digit := sum%10
lst = Push(lst, digit)
}else {
lst = Push(lst, sum)
}
tempNode = tempNode.Next
}
if remain != 0{
lst = Push(lst, remain)
}
return lst
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment