leetcode--(2. Add Two Numbers)

题目描述:

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
}

 

posted @ 2017-08-19 14:42  孤独风中一匹狼  阅读(198)  评论(0编辑  收藏  举报