题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
package main
import . "nc_tools"
/*
* type ListNode struct{
* Val int
* Next *ListNode
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
func reverseList(h *ListNode) *ListNode {
var res *ListNode
for h != nil {
tmpNext := h.Next
h.Next = res
res = h
h = tmpNext
}
return res
}
func addInList(head1 *ListNode, head2 *ListNode) *ListNode {
// write code here
rh1 := reverseList(head1)
rh2 := reverseList(head2)
var res *ListNode
curV := 0
curOffset := 0
for rh1 != nil || rh2 != nil {
v1 := 0
v2 := 0
if rh1 != nil {
v1 = rh1.Val
rh1 = rh1.Next
}
if rh2 != nil {
v2 = rh2.Val
rh2 = rh2.Next
}
tmpV := v1 + v2 + curOffset
curV = tmpV % 10
curOffset = tmpV / 10
tmpNode := ListNode{
Val: curV,
Next: res,
}
res = &tmpNode
}
if curOffset > 0 {
tmpNode := ListNode{
Val: curOffset,
Next: res,
}
res = &tmpNode
}
return res
}
