leetcode2-两数(链表)相加
- 构建链表:先建链表头head,再建链表尾巴(引用传递)tail:=head,之后若是有新节点加入,则使用tail.Next = new(ListNode)进行新增
- 链表节点创建方法: head := &ListNode{Val:1}
- 用单链表描述两数,758: 7->5->8
- 求和方法,从链表头至链表尾依次遍历,把两链表相同位置的节点进行相加,两数之和取余为本位值,两数之和取模为进位值
- 返回值为指针
func addTwoNumbers(l1 *ListNode,l2 *ListNode) *ListNode{
head := new(ListNode)
tail := head
carry := 0
for l1 != nil || l2 != nil || carry > 0 {
tail.Next = new(ListNode)
tail = tail.Next
if l1 != nil {
carry += l1.Val
l1 = l1.Next
}
if l2 != nil {
carry += l2.Val
l2 = l2.Next
}
curr.Val = carry % 10
carry /= 10
}
return head.Next
}