题解 | #两个链表生成相加链表#反转链表后相加,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;
    }
}
全部评论

相关推荐

09-28 09:18
吉首大学 Java
离上岸不远了的牛油很...:同27,你写的专业技能那些是真熟练了吗,我感觉稍微问深一点我都要🐔
你找实习最大的坎坷是什么
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

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