码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode--(2. Add Two Numbers)

时间:2017-08-19 15:05:11      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:empty   tput   tco   store   ber   nod   put   leetcode   style   

题目描述:

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 l3 =&ListNode{}
    q:=l3
    c:=0
    for l1!=nil&&l2!=nil{
        p:=&ListNode{}
        sum:=l1.Val+l2.Val+c
        p.Val=sum%10
        q.Next=p
        q=p
        c=sum/10
        l1=l1.Next
        l2=l2.Next

    }
    for l1!=nil{
        p:=&ListNode{}
        sum:=l1.Val+c
        p.Val=sum%10
        q.Next=p 
        q=p 
        c=sum/10
        l1=l1.Next    
    }
    for l2!=nil{
        p:=&ListNode{}
        sum:=l2.Val+c
        p.Val=sum%10
        q.Next=p 
        q=p 
        c=sum/10
        l2=l2.Next    
    }
    for c>0{
        p:=&ListNode{}
        p.Val=c%10
        c=c/10
        q.Next=p 
        q=p 
    }
    return l3.Next
}

 

leetcode--(2. Add Two Numbers)

标签:empty   tput   tco   store   ber   nod   put   leetcode   style   

原文地址:http://www.cnblogs.com/fwdqxl/p/7396532.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!