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

链表相加(二)

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;
    }
}
全部评论

相关推荐

09-17 20:37
已编辑
长沙学院 Java
涂莱:学院本重心后移,金10银11,甚至金11银12,战线拉长一点,对于学院本来说秋招是个持久战,加油吧
听劝,我这个简历该怎么改...
点赞 评论 收藏
分享
牛油果甜奶昔:别的先不说,牛客还能内推护士?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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