题解 | #两个链表生成相加链表#反转链表后相加,40行代码搞定,参考大数相加

两个链表生成相加链表

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

import java.util.*;
public class Solution {
    public ListNode addInList (ListNode head1, ListNode head2) {
        head1 = reverseList(head1);
        head2 = reverseList(head2);
        int carry = 0;
        ListNode dumpy = new ListNode(-1);
        ListNode cur = dumpy;
        while(head1!=null || head2!=null || carry!=0){
            int x = 0;
            int y = 0;
            if(head1!=null){
                x = head1.val;
                head1 = head1.next;
            }
            if(head2!=null){
                y = head2.val;
                head2 = head2.next;
            }
            int sum = x+y+carry;
            carry = sum/10;
            cur.next = new ListNode(sum%10);
            cur = cur.next;
        }
        return reverseList(dumpy.next);
    }

    public ListNode reverseList(ListNode head){
        ListNode cur = head;
        ListNode pre = null;
        ListNode next = null;
        while(cur!=null){
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
}
全部评论

相关推荐

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