leetcode2-两数(链表)相加

leetcode2-两数(链表)相加

  • 构建链表:先建链表头head,再建链表尾巴(引用传递)tail:=head,之后若是有新节点加入,则使用tail.Next = new(ListNode)进行新增
  • 链表节点创建方法: head := &ListNode{Val:1}
  • 用单链表描述两数,758: 7->5->8
  • 求和方法,从链表头至链表尾依次遍历,把两链表相同位置的节点进行相加,两数之和取余为本位值,两数之和取模为进位值
  • 返回值为指针
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
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
}
posted @ 2020-08-09 17:27  litchi99  阅读(100)  评论(0编辑  收藏  举报