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

链表相加(二)

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

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param head1 ListNode类
     * @param head2 ListNode类
     * @return ListNode类
     */
    public ListNode addInList (ListNode head1, ListNode head2) {
        // write code here
        head1 = reverse(head1);
        head2 = reverse(head2);
        ListNode dummy = new ListNode(-1);
        ListNode cur = dummy;
        int add = 0;
        while (head1 != null || head2 != null) {
            int x = head1 == null ? 0 : head1.val;
            int y = head2 == null ? 0 : head2.val;
            if(head1 != null)head1 = head1.next;
            if(head2 != null)head2 = head2.next;
            int sum = x + y + add;
            cur.next = new ListNode(sum % 10);
            cur = cur.next;
            add = sum / 10;
        }
        if (add != 0)
            cur.next = new ListNode(add);
        return reverse(dummy.next);
    }
    private ListNode reverse(ListNode head) {
        ListNode pre = null, cur = head, next = null;
        while (cur != null) {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
}

先翻转链表,才能从低位开始相加,最后结果需要翻转

全部评论

相关推荐

投递长鑫存储等公司8个岗位
点赞 评论 收藏
分享
Rena1ssanc...:对的,要是面评没太烂,勤更新简历等捞就行了,腾讯可以无限复活
点赞 评论 收藏
分享
05-13 02:01
已编辑
惠州学院 前端工程师
安静的少年在求佛:建议把公司名字写到标题。以后有人想搜就能直接搜到
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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