传送门
牛客面试笔试必刷101题 ----------------链表相加(二)
题目以及解析
题目
解题代码及解析
解析
这一道题主要是要对链表相加的过程进行模拟,虽然思路不难但是细节出比较多,这里博主的思路主要是先将两个链表反转过来然后以Head1
为基础来模拟相加过程,最后将答案链表再反转回来
代码
package mainimport (_ "fmt". "nc_tools"
)/** type ListNode struct{* Val int* Next *ListNode* }*//*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可*** @param head1 ListNode类* @param head2 ListNode类* @return ListNode类*/func ReserveList(head *ListNode) *ListNode {var prev *ListNode = nilcurrent := headfor current != nil {next := current.Nextcurrent.Next = prevprev = currentcurrent = next}return prev
}func add(val1, val2, plus int) (int, int) {result := val1 + val2 + plusif result > 9 {plus = 1} else {plus = 0}result = result % 10return result, plus
}func addInList(head1 *ListNode, head2 *ListNode) *ListNode {Head1 := ReserveList(head1)Head2 := ReserveList(head2)result := Head1var phead *ListNodeplus := 0for Head1 != nil || Head2 != nil {if Head1 != nil && Head2 != nil {Head1.Val, plus = add(Head1.Val, Head2.Val, plus)phead=Head1Head1 = Head1.NextHead2 = Head2.Next} else if Head1 != nil {Head1.Val, plus = add(Head1.Val, 0, plus)phead.Next= Head1Head1 = Head1.Nextphead = phead.Next} else {Head2.Val, plus = add(0, Head2.Val, plus)phead.Next = Head2Head2 = Head2.Nextphead = phead.Next}}if plus > 0 {Node := &ListNode{Val: 1}phead.Next = Nodephead = phead.Next}return ReserveList(result)
}