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

链表相加(二)

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

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    public ListNode addInList (ListNode head1, ListNode head2) {
        if (head1 == null || head2 == null) return head1 == null ? head2 : head1;
        head1 = reverse(head1);
        head2 = reverse(head2);
        ListNode dummy = new ListNode(0);
        ListNode Head = dummy;
        int sum,v1,v2, carry = 0;
        while (head1 != null || head2 != null){
            v1 = 0;
            v2 = 0;
            if (head1 != null){
                v1 = head1.val;
                head1 = head1.next;
            }
            if (head2 != null){
                v2 = head2.val;
                head2 = head2.next;
            }
            sum = v1 + v2 + carry;
            carry = sum / 10;
            Head.next = new ListNode(sum % 10);
            Head = Head.next;
        }
        if (carry != 0){
            Head.next = new ListNode(carry);
        }
        return reverse(dummy.next);
    }

    private ListNode reverse(ListNode head){
        ListNode next,pre = null;
        while (head != null){
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }
}
全部评论

相关推荐

04-12 13:42
江南大学 C++
点赞 评论 收藏
分享
05-07 17:58
门头沟学院 Java
wuwuwuoow:1.简历字体有些怪怪的,用啥写的? 2.Redis 一主二从为什么能解决双写一致性? 3.乐观锁指的是 SQL 层面的库存判断?比如 stock > 0。个人认为这种不算乐观锁,更像是乐观锁的思想,写 SQL 避免不了悲观锁的 4.奖项证书如果不是 ACM,说实话没什么必要写 5.逻辑过期时间为什么能解决缓存击穿问题?逻辑过期指的是什么 其实也没什么多大要改的。海投吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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