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

链表相加(二)

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

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务