题解 | #链表相加(二)#

链表相加(二)

https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b

package main
import . "nc_tools"
/*
 * type ListNode struct{
 *   Val int
 *   Next *ListNode
 * }
 */

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param head1 ListNode类 
 * @param head2 ListNode类 
 * @return ListNode类
*/
func translist (head *ListNode) *ListNode{
     var newHead *ListNode
     if head == nil || head.Next ==nil{
        return head
    }
    for head!=nil{
        temp := head.Next
        head.Next = newHead
        newHead = head
        head = temp
    }
    return newHead
}
func addInList( head1 *ListNode ,  head2 *ListNode ) *ListNode {
    // write code here
    head1 = translist(head1)
    head2 = translist(head2)
    head := &ListNode{-1,nil}
    nhead :=head
    tmp := 0
    for head1 != nil || head2!=nil{
           val := tmp
        if head1 != nil {
            val = val+head1.Val
            head1=head1.Next
        }
        if head2 != nil{
            val = val+head2.Val
            head2=head2.Next
        }
        tmp = val/10
        nhead.Next = &ListNode{val%10,nil}
        nhead = nhead.Next
    }
    if tmp >0 {
        nhead.Next =&ListNode{tmp,nil}
    }
    return translist(head.Next)

    
}

全部评论

相关推荐

05-19 19:57
蚌埠学院 Python
2237:Gpa70不算高,建议只写排名,个人技能不在多而在精,缩到8条以内。项目留一个含金量高的,减少间距弄到一页,硕士简历也就一页,本科不要写很多
实习,投递多份简历没人回...
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-03 18:22
投了几百份简历,专业和方向完全对口,都已读不回。尝试改了一下学校,果然有奇效。
steelhead:这不是很正常嘛,BOSS好的是即便是你学院本可能都会和聊几句,牛客上学院本机会很少了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务