Add Two Numbers

来源:互联网 发布:富贵鸡源码 编辑:程序博客网 时间:2024/05/17 06:08

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

/** * Definition for singly-linked list. * type ListNode struct { *     Val int *     Next *ListNode * } *//**  * 思路很简单同时遍历两个链表即可**/func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {var result = new(ListNode)result.Val = -1var tmpre = resultvar add  = 0for (l1 != nil || l2 != nil) {var v1 = 0var v2 = 0if (l1 != nil){v1 = l1.Val}if (l2 != nil){v2 = l2.Val}var sum = v1 + v2 + addif tmpre.Val == -1 {tmpre.Val = sum % 10}else {var tmp = new(ListNode)tmp.Val = sum % 10tmpre.Next = tmptmpre = tmp}add = sum / 10if (l1 != nil){l1 = l1.Next}if (l2 != nil) {l2 = l2.Next}}if add > 0 {var tmp = new(ListNode)tmp.Val = addtmpre.Next = tmp}return result}



原创粉丝点击